1. 程式人生 > >SQL按時間分段分組統計資料

SQL按時間分段分組統計資料

sql中按照時間分段分組,顯示及統計分段資料,最後獲取總行數:

下面sql條件中48表示時間段數(一天48個0.5小時即半小時分段統計,以此類推修改);--註釋了查詢條件即只統計錯誤或統計時間限制(hh24miss)內的資料;最後0和500分別為分頁起止數。
查詢行資料

select *
  from (select rownum as rn, a.*
          from (select to_char((d.timepoint - 1 / 48),'yyyy-mm-dd hh24:mi:ss') starttime,       --臨時表d儲存了分好了的今天的各時間段
                       to_char(timepoint,'yyyy-mm-dd hh24:mi:ss') endtime,
                       t.jobid,
                       sum(count) updateTimes,
                       sum(decode(status, 2, 1, 0)) failTimes,
                       sum(cost) totalCost,
                       sum(rowsize) updateSize
                  from kdgs_realtime_log t,
                       (select to_date('20171017', 'YYYYMMDD') + 1 -
                               (level - 1) / 48 timepoint
                          from dual
                        connect by level <= 48) d
                 where t.jobid = 1000009
                   and t.kddate = 20171017
                   and to_date(t.updatetime, 'YYYYMMDDHH24MISS') <
                       d.timepoint
                   and to_date(t.updatetime, 'YYYYMMDDHH24MISS') >=
                       d.timepoint - 1 / 48
                --        AND t.status = '2'
                --and substr(t.updatetime,9,6) >=161010
                --and substr(t.updatetime,9,6) <=183000
                 group by d.timepoint, t.jobid
                 order by starttime) a
         where rownum <= 500) tt
 where tt.rn > 0

總行數:

select count(1)
  from (select count(1)
          from kdgs_realtime_log t,
               (select to_date('20171017', 'YYYYMMDD') + 1 - (level - 1) / 48 timepoint
                  from dual
                connect by level <= 48) d
         where t.jobid = 1000009
           and to_date(t.updatetime, 'YYYYMMDDHH24MISS') < d.timepoint
           and to_date(t.updatetime, 'YYYYMMDDHH24MISS') >=
               d.timepoint - 1 / 48
        --        AND t.status = '2'
        --and substr(t.updatetime,9,6) >=161010
        --and substr(t.updatetime,9,6) <=183000
         group by d.timepoint, t.jobid)