我是SQL新手所以请原谅我这个天真的问题。
我有一个日期范围说'20180903 - 20180905'所以从3rd Sep to 5th Sep
3天。
现在每天我们有24个军事小时,范围从0-23
,我们写了a range of 4 at a time in a single day
的查询。
所以,假设,
select
COUNT(wk_id),
SUM(total_occurances) as total_wk_occurances,
SUM(SUCCEEDED_instances) as total_successful_occurances,
SUM(FAILED_instances) as total_error_occurances
from
(
select w1.wk_id,
COUNT(w1.wk_occurance_id) as total_occurances,
sum(case when w1.status='SUCCEEDED' then 1 else 0 end ) as SUCCEEDED_instances,
sum(case when w1.status !='SUCCEEDED' then 1 else 0 end ) as FAILED_instances
from
work_instances w1
inner join
time_table td2
on
w1.end_time = td2.time_id
where
(td2.military_hour between 0 and 3 and end_date='20180903') group by w1.wf_id
) as sub_q1
现在我已经采取了20180903
军事小时范围0-3
。它返回一行像
46 | 224 | 208 | 16
我是否应该使用像4-7, 8-11, 12- 15, 16-19, 20 - 23
这样的范围再写相同的查询五次?然后聚合并返回6行的查询集?
我怎样才能更好地写出来?
此外,它只适用于20180903
。
如果对于其他2 days and return all 18 rows each(6 each day)
该怎么办?
EG
结果集可能看起来像
COUNT | total_wk_occurances | total_succeessful_occurances | total_error_Occurances
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
46 | 224 | 208 | 16
34 | 100 | 75 | 25
使用条件聚合和group by
。像这样的东西:
select end_date,
(floor(td2.military_hour / 4) * 4) as military_hour,
count(w1.wk_occurance_id) as total_occurances,
sum( (w1.status = 'SUCCEEDED')::int ) as SUCCEEDED_instances,
sum( (w1.status <> 'SUCCEEDED')::int ) as FAILED_instances
from work_instances w1 inner join
time_table td2
on w1.end_time = td2.time_id
where end_date >= 20180901' and end_date <2018
group by end_date, (floor(td2.military_hour / 4) * 4)