如何从组中获得百分比?

时间:2014-08-14 15:10:32

标签: sql postgresql aggregate-functions window-functions

问题:我想知道0到3之间,3到5之间等高度的百分比等。

我可以在这里计算绝对值:

SELECT t.classes, count(*) FROM (select case 
    WHEN height BETWEEN 0 and 3 then 0 
    WHEN height BETWEEN 3 and 5 then 1 
    WHEN height BETWEEN  5 and 7 then 2
    WHEN height BETWEEN 7 and 9 then 3
    WHEN height BETWEEN 9 and 11 then 4
    WHEN height > 11 then 5
    end as classes from lkp0201val) t, group by classes order by classes

我可以计算总分数:

select count(*) from lkp0101val;

...但我现在不知道如何将该计数值应用于第一个陈述。

2 个答案:

答案 0 :(得分:1)

您可以使用窗口函数来获取总数:

SELECT t.classes, count(*),
       1.0*count(*) / sum(count(*)) over () as proportion
FROM (select (case WHEN height BETWEEN 0 and 3 then 0 
                   WHEN height BETWEEN 3 and 5 then 1 
                   WHEN height BETWEEN  5 and 7 then 2
                   WHEN height BETWEEN 7 and 9 then 3
                   WHEN height BETWEEN 9 and 11 then 4
                   WHEN height > 11 then 5
              end) as classes
      from lkp0201val
     ) t
group by classes
order by classes;

答案 1 :(得分:1)

这里不需要子查询:

SELECT CASE WHEN height BETWEEN 0 AND 3  THEN 0 
            WHEN height BETWEEN 3 AND 5  THEN 1 
            WHEN height BETWEEN 5 AND 7  THEN 2
            WHEN height BETWEEN 7 AND 9  THEN 3
            WHEN height BETWEEN 9 AND 11 THEN 4
            WHEN height             > 11 THEN 5
       END AS class
      ,count(*) AS ct
      ,round(count(*) * 100.0 / sum(count(*)) OVER (), 2) AS percentage
FROM   lkp0201val
GROUP  BY 1
ORDER  BY 1;

返回实际百分比,四舍五入为2位小数。

在旧版本(或某些其他没有窗口函数的RDBMS)中,您可以用一个简单的子查询替换它来计算总数:

...
  ,round(count(*) * 100.0 / (SELECT count(*) FROM lkp0201val), 2) AS percentage
...