我想有条件地计算中位数,例如,对性别变量中的男性和女性说。我想使用这里提供的以下两个备选代码之一http://sqlperformance.com/2012/08/t-sql-queries/median作为计算中位数的最快方法。
备选方案1
DECLARE @c BIGINT = (SELECT COUNT(*) FROM dbo.EvenRows);
SELECT AVG(1.0 * val)
FROM (
SELECT val FROM dbo.EvenRows
ORDER BY val
OFFSET (@c - 1) / 2 ROWS
FETCH NEXT 1 + (1 - @c % 2) ROWS ONLY
) AS x;
备选方案2
SELECT @Median = AVG(1.0 * val)
FROM
(
SELECT o.val, rn = ROW_NUMBER() OVER (ORDER BY o.val), c.c
FROM dbo.EvenRows AS o
CROSS JOIN (SELECT c = COUNT(*) FROM dbo.EvenRows) AS c
) AS x
WHERE rn IN ((c + 1)/2, (c + 2)/2);
在哪里放GROUP
声明?有人可以建议我如何使用参数MEDIAN(ColumnToCalculateMedian, ColumnContaingSex)