我对Oracle比较陌生,所以我真的很感激一些帮助。
我有一个类似的查询:
SELECT * FROM reservations WHERE date between (date1) and (date2).
我需要的是在间隔期内获得所有预订:今天的日期和今天的日期 - 1年,所以基本上是1年的历史。
我想以1个月的间隔运行上述查询,并将查询集导出为excel。 我需要一些关于循环逻辑的帮助(创建一个存储过程或函数),因为我稍后会想到导出到excel。
答案 0 :(得分:1)
这将提供从1年回到今天的所有记录:
SELECT * FROM reservations
WHERE date >= trunc( sysdate ) - interval '1' year
AND date < trunc( sysdate ) + interval '1' day
我想以1个月的间隔运行上述查询,
据我所知,您希望运行此查询12次,每次都是另一个月期。如果是,则运行此查询12次,更改参数X(在SELECT 1 As X FROM dual
子查询内),从12开始到1(或1到12):
SELECT * FROM reservations
CROSS JOIN (
SELECT 1 As X FROM dual
) x
WHERE date >= trunc( sysdate ) - x * interval '1' month
AND date < trunc( sysdate ) + interval '1' day - ( x - 1 ) * interval '1' month
答案 1 :(得分:0)
Here is the procedure to create the queries month-wise starting from sysdate .
create or replace procedure monthwise_query
as
t_date DATE := TRUNC(SYSDATE) ;
c_date DATE ;
BEGIN
FOR i in 1..12
LOOP
c_date := t_date;
dbms_output.put_line('select * from reservations where rev_date between to_date('''||c_date||''',''DD-MON-YY'') and (select add_months(to_date('''||c_date||''',''DD-MON-YY''),-1) from dual);');
select add_months(c_date,-1)
into t_date
from dual;
END LOOP;
END;
- It can be extended with UTIL_FILE utility inside this procedure to write each query result to single/multiple files.
- SPOOL from SQL*plus for each query will be easy
- UNIX script to loop through each monthwise-query to load to file also possible