按日期和日期分组

时间:2014-02-06 12:02:16

标签: sql oracle group-by

我有一个带日期的会话活动表。

sess_actv (id number,actv number,start_date TIMESTAMP(3))

我希望白天和我的工作时间(上午8点到晚上8点),非工作时间(其余时间)的活动总和。因此,每天我都会获得2行,一组工作时间和一组工作时间。

像这样:

select sum(actv), 'work/off hours'
from sess_actv
group by 'work and off hours';

示例表数据

id      actv        start_date 
---     -----       ------------
1       2           21-NOV-13 2.30.02.358 am    
2       4           21-NOV-13 10.30.02.358 am
3       7           21-NOV-13 2.30.02.358 pm
4       1           21-NOV-13 10.30.02.358 PM
5       7           22-NOV-13 2.30.02.358 pm
6       1           22-NOV-13 10.30.02.358 PM

查询应返回:

date                    sum(actv)
-----                   ----------
Thursday work hours     11      
Thursday off hours      3       
friday work hours       7       
friday off hours        1       

1 个答案:

答案 0 :(得分:1)

此版本将您想要的内容放在三列中:

select to_char(start_date, 'Day') as dow,
       (case when extract(hour from start_date) between 8 and 19
             then 'work/on hours'
             else 'work/off hours'
        end) as period,
       sum(actv)
from sess_actv
group by to_char(start_date, 'Day'),
         (case when extract(hour from start_date) between 8 and 19
               then 'work/on hours'
               else 'work/off hours'
          end)