Function to Calculate Median in SQL Server

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

    DECLARE @Obs int
    DECLARE @RowAsc table
    (
    ID      INT IDENTITY,
    Observation  FLOAT
    )
    INSERT INTO @RowAsc
    SELECT Observations FROM MyTable
    ORDER BY 1 
    SELECT @Obs=COUNT(*)/2 FROM @RowAsc
    SELECT Observation AS Median FROM @RowAsc WHERE ID=@Obs
    

提交回复
热议问题