Function to Calculate Median in SQL Server

前端 未结 30 3370
孤独总比滥情好
孤独总比滥情好 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:30

    I wanted to work out a solution by myself, but my brain tripped and fell on the way. I think it works, but don't ask me to explain it in the morning. :P

    DECLARE @table AS TABLE
    (
        Number int not null
    );
    
    insert into @table select 2;
    insert into @table select 4;
    insert into @table select 9;
    insert into @table select 15;
    insert into @table select 22;
    insert into @table select 26;
    insert into @table select 37;
    insert into @table select 49;
    
    DECLARE @Count AS INT
    SELECT @Count = COUNT(*) FROM @table;
    
    WITH MyResults(RowNo, Number) AS
    (
        SELECT RowNo, Number FROM
            (SELECT ROW_NUMBER() OVER (ORDER BY Number) AS RowNo, Number FROM @table) AS Foo
    )
    SELECT AVG(Number) FROM MyResults WHERE RowNo = (@Count+1)/2 OR RowNo = ((@Count+1)%2) * ((@Count+2)/2)
    

提交回复
热议问题