我有两个具有相似数据的查询(一个具有前一个周期,另一个具有当前周期)。我需要在剑道折线图中显示它。我怎么能这样做**
select date_trunc('hour' , "CreateDateTime"::TIMESTAMP) as c,
count(1) as d
from "ROBOT"
where "CreateDateTime"::TIMESTAMP between '2018-04-01' and '2018-04-22'
group by date_trunc('hour', "CreateDateTime"::TIMESTAMP)
UNION ALL
select date_trunc('hour' , "CreateDateTime"::TIMESTAMP) as a,
count(1) as b
from "ROBOT"
where "CreateDateTime"::TIMESTAMP between '2018-05-01' and '2018-05-22'
group by date_trunc('hour', "CreateDateTime"::TIMESTAMP);
答案 0 :(得分:1)
看起来你想要两个月的小时计数。假设这是正确的,你想要像:
select date_part('hour', "CreateDateTime"::TIMESTAMP) as hour,
sum(case when "CreateDateTime"::TIMESTAMP between '2018-04-01' and '2018-04-22' then 1 else 0 end) as apr,
sum(case when "CreateDateTime"::TIMESTAMP between '2018-05-01' and '2018-05-22' then 1 else 0 end) as may
from "ROBOT"
where "CreateDateTime"::TIMESTAMP between '2018-04-01' and '2018-04-22'
or "CreateDateTime"::TIMESTAMP between '2018-05-01' and '2018-05-22'
group by 1;
当您想要使用不同标准从相同数据生成多个总和时,sum(case ...)模式是一个很好的模式。