【问题标题】:Oracle select between time and group the count based on each time periodOracle在时间之间选择并根据每个时间段对计数进行分组
【发布时间】:2014-04-07 09:41:16
【问题描述】:

我有一个包含一些信息和时间示例的表格

+----+-------------------+
| ID |     DateTime      |
+----+-------------------+
| 1  | 10/1/2014 10:10AM |
| 2  | 10/1/2014 11:00AM |
| 3  | 10/1/2014 12:00AM |
| 4  | 10/1/2014 14:10AM |
| 1  | 10/1/2014 02:30AM |
| 2  | 10/1/2014 10:10AM |
| 1  | 10/1/2014 10:40AM |
+----+-------------------+

我想进行这样的计数选择

from 10:00 to 11:00  ID 1  2 counts    ID 2    1 count
from 11:00 to 12:00  ID 3  1 count
from 14:00 to 15:00  ID 4  1 count
from 02:00 to 03:00  ID 1  1 count

所以我想按小时对搜索进行分组,并计算每小时内的每个 ID 我如何在 oracle 选择语句中做到这一点

【问题讨论】:

  • 我会研究“日历表”的创建。一个包含您需要报告的每一天的每个小时时段。然后,您的查询只是将日历表过滤到所需的行,然后加入数据的情况。这不仅有助于提高性能,而且还使查询更简单、更整洁。它甚至可以轻松获得输入记录为 0 小时的结果(仅使用左连接)。
  • 14:10AM 并不完全有意义 - 首先,因为您不能将 AM/PM 和 24 小时值结合起来,其次,因为 14:10 是下午(至少应该是 PM) .

标签: sql oracle select


【解决方案1】:

我会为此使用三个步骤:

  • 提取小时部分;你可以使用TRUNC(..., 'HH')
  • 使用带有小时和 ID 的 GROUP BY 计算单个计数
  • 透视这些结果(使用内置的 PIVOT 函数或使用 GROUP BY / SUM)

总而言之(使用 GROUP BY 和 SUM):

with v_data as (
  select 1 as id, to_date('2014-01-10 10:10:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 2 as id, to_date('2014-01-10 11:00:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 3 as id, to_date('2014-01-10 12:00:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 4 as id, to_date('2014-01-10 14:10:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 1 as id, to_date('2014-01-10 02:30:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 2 as id, to_date('2014-01-10 10:10:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual union all
  select 1 as id, to_date('2014-01-10 10:40:00', 'YYYY-MM-DD hh24:mi:ss') as datetime from dual 
) 
select hour, 
  sum(case when id = 1 then cnt else 0 end) as id1,
  sum(case when id = 2 then cnt else 0 end) as id2,
  sum(case when id = 3 then cnt else 0 end) as id3,
  sum(case when id = 4 then cnt else 0 end) as id4
from (  
  select 
    id, hour, count(*) as cnt 
  from (
    select 
      d.*, 
      trunc(datetime, 'HH') as hour
    from v_data d
  )
  group by id, hour
) 
group by hour
order by hour

这仅在 ID 列表固定时有效 - 如果您需要动态 ID 列表,则必须求助于动态 SQL。

【讨论】:

    猜你喜欢
    • 2015-03-07
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多