计算表格的中间值

时间:2013-03-05 16:41:42

标签: sql pivot median

我需要计算包含各种年龄范围的表格列值的中位数,并且我无法找到问题的答案。该表的结构如下:

ID    0-5    5-10    11-15    16-20   ...
------------------------------------------
1     14     5       12       5       ...
2     5      11      14       17      ...

我已经阅读过使用rowcount和aggregate来查找数据中位数,但这似乎要求数据都在同一列中。因此,我认为我需要在SQL中使用PIVOT函数,但我无法弄清楚所需的语法。任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分:2)

你真正想要的是一个UNPIVOT:

SELECT ID, Value, AgeRange
FROM 
   (SELECT *
   FROM ages) pivotedDate
UNPIVOT
   (Value FOR AgeRAnge IN 
      ([0-5], [6-10], ...)
) AS Result;

请注意,您必须将所有年龄段放在语句中以返回其值。

答案 1 :(得分:2)

没有一种方法非常优雅。我会选择蛮力:

select id,
       (case when tot1 >= totn / 2 then 'col1'
             when tot2 >= totn / 2 then 'col2'
        . . .
       ) as mediancolumn
from (select t.*,
             col1 as Tot1,
             col1 + col2 as Tot2,
             . . .
             (col1 + col2 + . . . coln) as Totn
      from t
     ) t

如果你真的想要解析范围,那么同样的想法就成立了。但是您需要更改then语句的case部分来处理数值。