针对不同的日期范围,在单个查询中获取多列计数

时间:2017-11-04 07:27:09

标签: mysql sql

几天前我的post之后,我们得到了理想的结果。 现在我们有了在图表上绘制事件计数的新要求,我们需要指定日期范围,结果将限制在日期范围(纪元)内。我能够通过以下两个单独的查询来完成它,但它似乎不是很好的选择。

问题

有没有其他方法可以在单个查询中组合这两个查询,并在不同的结果集中获取这两个查询的结果?

select source_id
       sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
       sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event where eventTime >= 1451606400 and eventTime <= 1454284800 
group by source_id;

select source_id
       sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
       sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event where eventTime >= 1456790400 and eventTime <= 1459468800
group by source_id;

1 个答案:

答案 0 :(得分:0)

select source_id
       sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
       sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event 
where (eventTime >= 1451606400 and eventTime <= 1454284800) OR
      (eventTime >= 1456790400 and eventTime <= 1459468800) 
group by source_id;