2

我需要运行此查询以获取 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')
4

3 回答 3

2

您始终可以生成您需要的日历并将其与您的查询结合起来。

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
于 2020-10-27T19:40:50.417 回答
1

它是行生成器。例如:

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.program, c.open_date, c.close_date
from clients c cross join period p
where open_date  = add_months(trunc(to_date(p.start_year, 'yyyy'), 'yyyy'), 12 * (level - 1))
  and close_date = add_months(trunc(to_date(p.start_year, 'yyyy'), 'yyyy'), 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, 'yyyy'), 'yyyy'), 12 * (level - 1)) a,
  5         add_months(trunc(to_date(p.start_year, 'yyyy'), 'yyyy'), 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>
于 2020-10-27T19:37:00.937 回答
1

看看下面的代码片段:

SELECT EXTRACT(YEAR FROM TO_DATE('01.01.2015', 'dd.mm.yyyy')) + ROWNUM - 1 AS "YEAR"
    FROM dual
CONNECT BY ROWNUM <= 5
于 2020-10-27T19:49:22.213 回答