Function to Calculate Median in SQL Server

前端 未结 30 2821
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:03

According to MSDN, Median is not available as an aggregate function in Transact-SQL. However, I would like to find out whether it is possible to create this functionality (u

30条回答
  •  -上瘾入骨i
    2020-11-22 04:22

    This works with SQL 2000:

    DECLARE @testTable TABLE 
    ( 
        VALUE   INT
    )
    --INSERT INTO @testTable -- Even Test
    --SELECT 3 UNION ALL
    --SELECT 5 UNION ALL
    --SELECT 7 UNION ALL
    --SELECT 12 UNION ALL
    --SELECT 13 UNION ALL
    --SELECT 14 UNION ALL
    --SELECT 21 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 29 UNION ALL
    --SELECT 40 UNION ALL
    --SELECT 56
    
    --
    --INSERT INTO @testTable -- Odd Test
    --SELECT 3 UNION ALL
    --SELECT 5 UNION ALL
    --SELECT 7 UNION ALL
    --SELECT 12 UNION ALL
    --SELECT 13 UNION ALL
    --SELECT 14 UNION ALL
    --SELECT 21 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 23 UNION ALL
    --SELECT 29 UNION ALL
    --SELECT 39 UNION ALL
    --SELECT 40 UNION ALL
    --SELECT 56
    
    
    DECLARE @RowAsc TABLE
    (
        ID      INT IDENTITY,
        Amount  INT
    )
    
    INSERT INTO @RowAsc
    SELECT  VALUE 
    FROM    @testTable 
    ORDER BY VALUE ASC
    
    SELECT  AVG(amount)
    FROM @RowAsc ra
    WHERE ra.id IN
    (
        SELECT  ID 
        FROM    @RowAsc
        WHERE   ra.id -
        (
            SELECT  MAX(id) / 2.0 
            FROM    @RowAsc
        ) BETWEEN 0 AND 1
    
    )
    

提交回复
热议问题