按时间段统计数据(1)
有这样一个表table1,两个字段,createtime和value,如下
2007-07-09 07:00:01 90
2007-07-09 08:05:31 78
2007-07-09 14:00:00 95
2007-07-09 21:15:01 20
2007-07-10 22:23:08 10
这个表每天,每分钟都会有数据。统计每天0点到8点,21点到23,value的总和,其它时间段不要。
--测试数据
create table t4(cdate date,cnum int)
insert into t4
select to_date( '2007-07-09 07:00:01 ', 'yyyy-mm-dd hh24:MI:SS) '),90 from dual union all
select to_date( '2007-07-09 08:05:31 ', 'yyyy-mm-dd hh24:MI:SS) '),78 from dual union all
select to_date( '2007-07-09 14:00:00 ', 'yyyy-mm-dd hh24:MI:SS) '),95 from dual union all
select to_date( '2007-07-09 21:15:01 ', 'yyyy-mm-dd hh24:MI:SS) '),20 from dual union all
select to_date( '2007-07-10 22:23:08 ', 'yyyy-mm-dd hh24:MI:SS) '),10 from dual;
--执行查询
select to_char(cdate, 'yyyy-mm-dd '),
sum(case when to_number(to_char( cdate, 'hh24 ' ))> 0 and to_number(to_char( cdate, 'hh24 ' )) <=8 then cnum else 0 end) "0~8 ",
sum(case when to_number(to_char( cdate, 'hh24 ' ))> 21 and to_number(to_char( cdate, 'hh24 ' )) <=23 then cnum else 0 end) "21~23 "
from t4
group by to_char(cdate, 'yyyy-mm-dd ')
--查询结果
2007-07-09 168 0
2007-07-10 0 10
2007-07-09 07:00:01 90
2007-07-09 08:05:31 78
2007-07-09 14:00:00 95
2007-07-09 21:15:01 20
2007-07-10 22:23:08 10
这个表每天,每分钟都会有数据。统计每天0点到8点,21点到23,value的总和,其它时间段不要。
--测试数据
create table t4(cdate date,cnum int)
insert into t4
select to_date( '2007-07-09 07:00:01 ', 'yyyy-mm-dd hh24:MI:SS) '),90 from dual union all
select to_date( '2007-07-09 08:05:31 ', 'yyyy-mm-dd hh24:MI:SS) '),78 from dual union all
select to_date( '2007-07-09 14:00:00 ', 'yyyy-mm-dd hh24:MI:SS) '),95 from dual union all
select to_date( '2007-07-09 21:15:01 ', 'yyyy-mm-dd hh24:MI:SS) '),20 from dual union all
select to_date( '2007-07-10 22:23:08 ', 'yyyy-mm-dd hh24:MI:SS) '),10 from dual;
--执行查询
select to_char(cdate, 'yyyy-mm-dd '),
sum(case when to_number(to_char( cdate, 'hh24 ' ))> 0 and to_number(to_char( cdate, 'hh24 ' )) <=8 then cnum else 0 end) "0~8 ",
sum(case when to_number(to_char( cdate, 'hh24 ' ))> 21 and to_number(to_char( cdate, 'hh24 ' )) <=23 then cnum else 0 end) "21~23 "
from t4
group by to_char(cdate, 'yyyy-mm-dd ')
--查询结果
2007-07-09 168 0
2007-07-10 0 10