日期:2014-05-17  浏览次数:20979 次

Oracle按时间嵌套查询问题?
要计算数据8小时均值的最大值。比如给出8点到10点这个时间范围。也就是8点求一个1-8点的均值,9点求2-9点的均值,10点求3-10点的均值,然后求这几个均值的最大值。
我想嵌套查询,可是不知道里面的时间怎么随着外层的时间变化?
以上只是个例子,实际应用可能是几天内某个时间段各时间点8小时均值的最大值。
请问高手,SQL语句怎么写?

------解决方案--------------------

with t1 as
(
     select 1 c1,to_date('2013-05-20 01:01:01','yyyy-mm-dd hh24:mi:ss') c2,100 c3 from dual union all
     select 2 c1,to_date('2013-05-20 02:01:01','yyyy-mm-dd hh24:mi:ss') c2,200 c3 from dual union all
     select 3 c1,to_date('2013-05-20 03:01:01','yyyy-mm-dd hh24:mi:ss') c2,300 c3 from dual union all
     select 4 c1,to_date('2013-05-20 04:01:01','yyyy-mm-dd hh24:mi:ss') c2,400 c3 from dual union all
     select 5 c1,to_date('2013-05-20 05:01:01','yyyy-mm-dd hh24:mi:ss') c2,500 c3 from dual union all
     select 6 c1,to_date('2013-05-20 06:01:01','yyyy-mm-dd hh24:mi:ss') c2,600 c3 from dual union all
     select 7 c1,to_date('2013-05-20 07:01:01','yyyy-mm-dd hh24:mi:ss') c2,700 c3 from dual union all
     select 8 c1,to_date('2013-05-20 08:01:01','yyyy-mm-dd hh24:mi:ss') c2,800 c3 from dual union all
     select 9 c1,to_date('2013-05-20 09:01:01','yyyy-mm-dd hh24:mi:ss') c2,900 c3 from dual union all
     select 10 c1,to_date('2013-05-20 10:01:01','yyyy-mm-dd hh24:mi:ss') c2,1000 c3 from dual union all
     select 11 c1,to_date('2013-05-20 11:01:01','yyyy-mm-dd hh24:mi:ss') c2,1100 c3 from dual union all
     select 12 c1,to_date('2013-05-20 12:01:01','yyyy-mm-dd hh24:mi:ss') c2,1200 c3 from dual
)

select to_char(d1,'yyyy-mm-dd') dt,to_char(d1,'hh24')
------解决方案--------------------
'-'
------解决方案--------------------
to_char(d2,'hh24') d_scope,avg(c3) c3
from 
(
select to_date('2013-05-20 '
------解决方案--------------------
lpad(8-8+level,2,'0')
------解决方案--------------------
':00:00','yyyy-mm-dd hh24:mi:ss') d1,
       to_date('2013-05-20 '
------解决方案--------------------
lpad(8+level-1,2,'0')
------解决方案--------------------
':00:00','yyyy-mm-dd hh24:mi:ss') d2
from dual
connect by level <= 12- 8 + 1 --8为起始小时 12为结束小时 都可以作为参数