如何在SQL Server中找到中位数

时间:2010-01-07 18:26:12

标签: sql tsql

我有一张单独的桌子,可以按照班级列出学生的分数。 例如,每个班级有30名学生,因此每个班级有30个分数。 我想为每个类的每个数据集做一个简单的报告,即平均值,中位数和模式。 因此,每个班级都有平均值,中位数和模式。 我知道SQL Server没有内置函数用于中值和模式,我找到了中值的示例SQL。但是,我找到的样本没有进行任何分组,我发现:

SELECT
(
 (SELECT MAX(Value) FROM
   (SELECT TOP 50 PERCENT Value FROM dbo.VOrders ORDER BY Value) AS H1)
 +
 (SELECT MIN(Value) FROM
   (SELECT TOP 50 PERCENT Value FROM dbo.VOrders ORDER BY Value DESC) AS H2)
) / 2 AS Median

是否可以修改添加组,以便我得到每个类的中值?


我不认为我很清楚,我希望SQL返回一个数据集,看起来像这样:

MEDIAN CLASS 
====== ===== 
 90     BIO 
 77     CHEM

1 个答案:

答案 0 :(得分:0)

这就是答案:

WITH CTE AS (
SELECT e_id, 
   scale, 
   ROW_NUMBER() OVER(PARTITION BY e_id ORDER BY scale ASC) AS rn,   
   COUNT(scale) OVER(PARTITION BY e_id) AS cn
FROM waypoint.dbo.ScoreMaster
WHERE scale IS NOT NULL
)
SELECT e_id,

cast(AVG (cast(scale as decimal(5,2))) as decimal(5,3)) as [AVG],
cast (STDEV(cast(scale as decimal(5,1))) as decimal(5,3)) as [STDDEV],   
AVG(CASE WHEN 2 * rn - cn BETWEEN 0 AND 2 THEN scale END) AS FinancialMedian,
MAX(CASE WHEN 2 * rn - cn BETWEEN 0 AND 2 THEN scale END) AS StatisticalMedian

from CTE
GROUP BY e_id