【发布时间】:2018-08-13 12:23:40
【问题描述】:
有一个这样的tableA:
我想收到这样的表格(按 startTime 和 endTime 分组,cnt 列中的 Severity 计数和不同列中每种 Severity 的计数):
简单计数(cnt 列)工作正常。但是对于另一个我厌倦了 CASE WHEN THEN 逻辑并且它似乎不起作用(例如第 10 行)。在这种情况下,您能帮我进行 SQL 查询吗?
【问题讨论】:
有一个这样的tableA:
我想收到这样的表格(按 startTime 和 endTime 分组,cnt 列中的 Severity 计数和不同列中每种 Severity 的计数):
简单计数(cnt 列)工作正常。但是对于另一个我厌倦了 CASE WHEN THEN 逻辑并且它似乎不起作用(例如第 10 行)。在这种情况下,您能帮我进行 SQL 查询吗?
【问题讨论】:
你需要条件聚合:
select starttime, endtime, count(*),
sum(case when severity = 'low' then 1 else 0 end),
sum(case when severity = 'med' then 1 else 0 end),
sum(case when severity = 'high' then 1 else 0 end)
from table t
group by starttime, endtime;
【讨论】:
试试下面的查询:with case when
select starttime, endtime, count(severity) as cnt, count(case when severity='LOW' then 1 end) cnt_low,count(case when severity='MED' then 1 end) cnt_med,count(case when severity='HIGH' then 1 end) as cnt_high
from tablename
group by starttime, endtime
【讨论】:
用例when和聚合函数sum
select startTime , endTime,count(*) as Cnt,
sum( case when Severity='MED' then 1 else 0 end) as cntMed,
sum( case when Severity='LOW' then 1 else 0 end) as cntLow,
sum( case when Severity='HIGH' then 1 else 0 end) as cntHIGH from yourtable
group by startTime , endTime
【讨论】: