用于分组值0-9,10.20的多个case语句

时间:2017-06-22 08:29:16

标签: sql postgresql postgresql-9.3 postgresql-9.4

我有下面的第一个案例陈述,我需要将其与下面的案例陈述合并,以便将值组合在一起,如下所示:

days range   | Activity_submit
-------------------------------------
   0-9       |        11
  10-19      |        14
  20-29      |         3 
 SELECT 
    events_raw.properties ->> 'days_before_stay' AS "Days_before_stay",
    COUNT(CASE WHEN ((events_raw.properties ->> 'event_type') LIKE 
    'fs_mystay_activity_submit') THEN 1 ELSE NULL END) AS "Request Count"
    FROM events_raw

与第一个

合并的第二个案例陈述
select events_raw.properties ->> 'days_before_stay' AS "Days_before_stay" [days range], count(*) as [number of occurences]
from (
  select case  
    when days between 0 and 9 then ' 0- 9'
    when days between 10 and 19 then '10-19'
    else '20-99' end as range
  from events_raw) 
group by 1

1 个答案:

答案 0 :(得分:0)

我没有看到你的表格结构,但这里是你可以逐个表达的例子。

SELECT 
    (id/10)*10 toOrder, -- addition field to sort by
    (id/10)*10 || ' - ' || ((id)/10+1)*10 AS range, 
    count(*) myCount
FROM report
GROUP BY 
    (id/10)*10,
    (id/10)*10 || ' - ' || ((id)/10+1)*10, -- group by expression
ORDER BY toOrder;

相反,如果是id,则可以使用任何整数字段。