Postgres COUNT个实例并放入"桶"

时间:2017-04-20 18:56:27

标签: sql postgresql

我有一个包含行的大表,每个表都有一个位置ID(C1,C2,C3 3 C1,C2 2 C5 1 C3,C5 2 )。在location_id列下面有多个相同值的实例。我想要做的是计算每个值出现的次数,然后将该值放入"桶中#34;

我尝试了这个,但结果却是" 500 +"桶。

location_id

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要两个级别的聚合:

SELECT (CASE WHEN cnt <= 25 THEN '1-25'
             WHEN cnt <= 500 THEN '26-500'
             ELSE '500+'
        END) as bucket, COUNT(*) as numlocations, SUM(cnt) as numTotal
FROM (SELECT location_id, count(*) as cnt
      FROM myTable
      GROUP BY location_id
     ) l
GROUP BY bucket
ORDER BY MIN(cnt);

答案 1 :(得分:1)

试试这个: -

    Select 
     CASE WHEN #_cnt >= 1 AND #_cnt<= 25 THEN '1-25'
     WHEN #_cnt > 25 AND #_cnt <= 500 THEN '26-500'
     WHEN #_cnt > 500  THEN '500+'
     ELSE 'nothing'
     end as bucket,
   count(*) as column1
    from
    (
    Select location_id, count(*) as #_cnt
    from
    myTable
    group by location_id
    ) a
group by bucket

感谢: - )