根据小时SQL计算

时间:2018-04-30 20:56:13

标签: sql hiveql

我如何获得每小时的计数?

select count_hr_1, count_hr_2, count_hr_3 from db.table where year=2018 and month=01 and day=02 and hour=01 OR hour=02 OR hour=03;

此SQL /查询可能无效,但我想获得小时1,2,3的计数

2 个答案:

答案 0 :(得分:1)

select sum(case when hour = 1 then 1 else 0 end) as count_hr_1, 
       sum(case when hour = 2 then 1 else 0 end) as count_hr_2, 
       sum(case when hour = 3 then 1 else 0 end) as count_hr_3
from db.table 
where year = 2018 
and month = 1 
and day = 2 
and hour in (1,2,3)

答案 1 :(得分:1)

如果您能够将结果集处理为多行而不是一行,则可以使用GROUP BY

select hour, count(*)
  from db.table
  where
    year = 2018
    and month = 1
    and day = 2
    and hour in (1, 2, 3)
  group by hour