【问题标题】:Group by date by day and group of hours按日期分组和按小时分组
【发布时间】:2014-02-06 20:18:31
【问题描述】:

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

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       

【问题讨论】:

  • 我不知道该怎么做。我设法按天和/或按小时分组,但不是按天按小时分组。
  • 这里有2个问题需要解决。 (1) 如何判断是工作时间还是下班时间?答案 = EXTRACT(HOUR from start_date) between 8 and 16 (2) 如何确定星期几?答案 = to_char(start_date,'DAY').

标签: sql oracle group-by


【解决方案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)

【讨论】:

    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 2019-01-07
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2015-05-07
    • 2020-10-26
    相关资源
    最近更新 更多