我有两个联合在一起的CTE产生以下结果:
date serie events
2019-05-09 hello 175
2019-05-02 hello 196
2019-05-09 goodbye 1
2019-05-02 goodbye 1
我想每天添加事件,以便
2019-05-09 total 176
2019-05-02 total 197
此刻我有类似的东西:
with hello_events as (
--- actual logic not interesting ---
)
, goodbye_events as (
--- actual logic not interesting ---
)
select * from hello_events
union all
select * from goodbye_events
如果我希望将第三组结果作为总和,我认为我需要做类似的事情
with hello_events as (
--- actual logic not interesting ---
)
, goodbye_events as (
--- actual logic not interesting ---
)
select * from hello_events
union all
select * from goodbye_events
union all
select date, "total", sum(events) as events
from hello_events, goodbye_events
where hello_events.date = goodbye_events.date
但这显然是不正确的。我想念什么?
答案 0 :(得分:2)
用以下内容替换内部查询:
select date, 'total' as total, sum(events) as events
from (
select * from hello_events
union all
select * from goodbye_events
) t
group by date
答案 1 :(得分:1)
仅group by
,如下所示:
with hello_events as (
--- actual logic not interesting ---
)
,goodbye_events as (
--- actual logic not interesting ---
)
,tmp_result as (
select * from hello_events
union all
select * from goodbye_events
)
select
date,
'total',
sum(events)
from
tmp_result
group by
date