oracle 求sql语句 按照日期范围分组查询。请务必写出测试过的代码,有难度才有进步,谢谢大家。

2024-11-24 04:38:43
推荐回答(1个)
回答1:

你把时间先说明白了

你一下给了三个时间呢,以哪个时间的范围为准啊

---------补充---------

问了你半天也不答,按startdate的时间为准了

--建表如下

create table test
(startdate date,
enddate date,
autualdate date,
"desc" varchar2(10),
"value" int)

--插入数据

insert into test values (to_date('2013-05-17','yyyy-mm-dd'),to_date('2013-05-17','yyyy-mm-dd'),to_date('2013-05-17','yyyy-mm-dd'),'a',100);
insert into test values (to_date('2013-05-18','yyyy-mm-dd'),to_date('2013-05-18','yyyy-mm-dd'),to_date('2013-05-18','yyyy-mm-dd'),'a',200);
insert into test values (to_date('2013-05-19','yyyy-mm-dd'),to_date('2013-05-19','yyyy-mm-dd'),to_date('2013-05-19','yyyy-mm-dd'),'a',300);
insert into test values (to_date('2013-05-23','yyyy-mm-dd'),to_date('2013-05-23','yyyy-mm-dd'),to_date('2013-05-23','yyyy-mm-dd'),'a',400);
insert into test values (to_date('2013-05-17','yyyy-mm-dd'),to_date('2013-05-17','yyyy-mm-dd'),to_date('2013-05-17','yyyy-mm-dd'),'b',800);
insert into test values (to_date('2013-05-23','yyyy-mm-dd'),to_date('2013-05-23','yyyy-mm-dd'),to_date('2013-05-23','yyyy-mm-dd'),'b',900);

 

with t as
(select rownum rn,to_char(trunc(to_date('2012-01-01','yyyy-mm-dd'),'d')+rownum*7+1,'yyyy-mm-dd') time1,
to_char(trunc(to_date('2012-01-01','yyyy-mm-dd'),'d')+(rownum+1)*7,'yyyy-mm-dd') time2
from all_objects where rownum<=100)
select case when '2013-05-17' between a.time1 and a.time2 then '2013-05-17' else a.time1 end
||'到'||case when '2013-06-23' between a.time1 and a.time2 then '2013-06-23' else a.time2 end 日期范围,b."desc" 指标描述,
nvl(sum(case when to_char(b.startdate,'yyyy-mm-dd') between a.time1 and a.time2 then b."value" end),0) 指标值
from
(select time1,time2 from t where rn between
(select rn from t where '2013-05-17' between time1 and time2)
and
(select rn from t where '2013-06-23' between time1 and time2)) a left join test b
on 1=1
group by a.time1,a.time2,b."desc"
order by a.time1,"desc"