我是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
之类的范围再写5次相同的查询?然后汇总并返回具有6行的查询集?
如何更好地编写它?
此外,它仅适用于20180903
。
如果其他2 days and return all 18 rows each(6 each day)
要怎么做?
例如
结果集可能看起来像
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
答案 0 :(得分:0)
使用条件聚合和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)