如何解决Oracle SQL:一年中循环
我需要运行此查询以获取5年数据(2015年至2019年),我想知道是否有一种方法可以自动循环显示年份,而不是手动更改年份(例如,从2015年到2016年),并且运行此查询5次?任何帮助将不胜感激!谢谢!
Select ID,program,open_date,close_date
From clients
Where open_date=to_date('01/01/2015','mm/dd/yyyy')
and close_date=to_date('12/31/2015','mm/dd/yyyy')
解决方法
您始终可以生成所需的日历并将其与查询一起加入。
with cal as (
select add_months(date '2015-01-01',(level - 1)*12) as start_dt,add_months(date '2015-12-31',(level - 1)*12) as end_dt
from dual
connect by level <= 5
)
Select c.ID,c.program,c.open_date,c.close_date
From clients c
join cal
on c.open_date=cal.start_dt and c.close_date=cal.end_dt
,
它是行发生器。例如:
SQL> with period (start_year,end_year) as
2 (select 2015,2020 from dual)
3 select d.dummy,p.start_year + level - 1 as year
4 from dual d cross join period p
5 connect by level <= end_year - start_year
6 order by year;
D YEAR
- ----------
X 2015
X 2016
X 2017
X 2018
X 2019
SQL>
应用于您的代码(无法测试,没有表):
with
period (start_year,end_year) as
(select 2015,2020 from dual),select c.id,c.close_date
from clients c cross join period p
where open_date = add_months(trunc(to_date(p.start_year,'yyyy'),12 * (level - 1))
and close_date = add_months(trunc(to_date(p.start_year,12 * (level )) - 1
connect by level <= p.end_year - p.start_year;
因为这些值产生了
SQL> with
2 period (start_year,end_year) as
3 (select 2015,2020 from dual)
4 select add_months(trunc(to_date(p.start_year,12 * (level - 1)) a,5 add_months(trunc(to_date(p.start_year,12 * (level )) - 1 b
6 from period p
7 connect by level <= end_year - start_year;
A B
---------- ----------
01.01.2015 31.12.2015
01.01.2016 31.12.2016
01.01.2017 31.12.2017
01.01.2018 31.12.2018
01.01.2019 31.12.2019
SQL>
,
看看下面的代码片段:
SELECT EXTRACT(YEAR FROM TO_DATE('01.01.2015','dd.mm.yyyy')) + ROWNUM - 1 AS "YEAR"
FROM dual
CONNECT BY ROWNUM <= 5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。