有这样一个表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的总和,其它时间段不要。
每小时的统计就很好写,像这样的就不知如何写了。

解决方案 »

  1.   

    是统计每天0点到8点,21点到23这两个时间段各有多少数据吗?如
    1日0-8   XXX
    1日21-23 XXX
    2日0-8   XXX
    ...
      

  2.   

    --测试数据
    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