Function to Calculate Median in SQL Server

前端 未结 30 2825
孤独总比滥情好
孤独总比滥情好 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条回答
  •  误落风尘
    2020-11-22 04:22

    The following solution works under these assumptions:

    • No duplicate values
    • No NULLs

    Code:

    IF OBJECT_ID('dbo.R', 'U') IS NOT NULL
      DROP TABLE dbo.R
    
    CREATE TABLE R (
        A FLOAT NOT NULL);
    
    INSERT INTO R VALUES (1);
    INSERT INTO R VALUES (2);
    INSERT INTO R VALUES (3);
    INSERT INTO R VALUES (4);
    INSERT INTO R VALUES (5);
    INSERT INTO R VALUES (6);
    
    -- Returns Median(R)
    select SUM(A) / CAST(COUNT(A) AS FLOAT)
    from R R1 
    where ((select count(A) from R R2 where R1.A > R2.A) = 
          (select count(A) from R R2 where R1.A < R2.A)) OR
          ((select count(A) from R R2 where R1.A > R2.A) + 1 = 
          (select count(A) from R R2 where R1.A < R2.A)) OR
          ((select count(A) from R R2 where R1.A > R2.A) = 
          (select count(A) from R R2 where R1.A < R2.A) + 1) ; 
    

提交回复
热议问题