我有一个包含一些信息和时间示例的表
+----+-------------------+
| 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 select statment中执行此操作
答案 0 :(得分:0)
我将使用三个步骤:
TRUNC(..., 'HH')
GROUP BY
计算个人计数,小时和ID 总而言之(使用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。