sql - Select data grouped by time over midnight -
i have table like:
id timevalue ----- ------------- 1 06.07.15 06:43:01,000000000 2 06.07.15 12:17:01,000000000 3 06.07.15 18:21:01,000000000 4 06.07.15 23:56:01,000000000 5 07.07.15 04:11:01,000000000 6 07.07.15 10:47:01,000000000 7 07.07.15 12:32:01,000000000 8 07.07.15 14:47:01,000000000 and want group data special times.
current query looks this:
select to_char(timevalue, 'yyyy\mm\dd'), count(id), sum(case when to_char(timevalue, 'hh24mi') <=700 1 else 0 end) morning, sum(case when to_char(timevalue, 'hh24mi') >700 , to_char(timevalue, 'hh24mi') <1400 1 else 0 end) daytime, sum(case when to_char(timevalue, 'hh24mi') >=1400 1 else 0 end) evening table timevalue >= to_timestamp('05.07.2015','dd.mm.yyyy') group to_char(timevalue, 'yyyy\mm\dd') and getting output
day overall morning daytime evening ----- --------- 2015\07\05 454 0 0 454 2015\07\06 599 113 250 236 2015\07\07 404 139 265 0 so fine grouping on same day (0-7 o'clock, 7-14 o'clock , 14-24 o'clock)
question is: how can group on midnight?
for example count 6-14 , 14-23 , 23-6 o'clock on next day.
i hope understand question. welcome improve upper query if there better solution.
edit: tested now: sql fiddle
the key adjust group by before 6am gets grouped previous day. after that, counts pretty straight-forward.
select to_char(case when extract(hour timevalue) < 6 timevalue - 1 else timevalue end, 'yyyy\mm\dd') day, count(*) overall, sum(case when extract(hour timevalue) >= 6 , extract(hour timevalue) < 14 1 else 0 end) morning, sum(case when extract(hour timevalue) >= 14 , extract(hour timevalue) < 23 1 else 0 end) daytime, sum(case when extract(hour timevalue) < 6 or extract(hour timevalue) >= 23 1 else 0 end) evening my_table timevalue >= to_timestamp('05.07.2015','dd.mm.yyyy') group to_char(case when extract(hour timevalue) < 6 timevalue - 1 else timevalue end, 'yyyy\mm\dd');
Comments
Post a Comment