[英]Oracle - How to repeat query for every year/month/week
我已經進行了一個查詢,以獲取我所選列的日期為2018年12月的行:
SELECT myColumn1, myColumn2
FROM MyTable
WHERE to_char(myColumn_DATE, 'YYYY/MM') = '2018/12'
這很簡單,我現在可以使用這些行來創建一些進一步的邏輯。 但是,如果我需要在給定的一年,甚至每個星期每個月重復一次呢?
我將查詢結果導出到單獨的excel表中,所以我想我必須每次都手動檢查正確的日期間隔,並且不能聚合整年/月/等的數據。 是不是有一些PL / SQL方法來避免這種繁瑣的重復?
假設你是從2018十二月一日,你的目的是為了填充表MyTable2
通過從表中的數據MyTable
。
首先,讓我們創建沒有數據的MyTable2
:
create table MyTable2 as
select myColumn1, myColumn2
from MyTable
where 1 = 9;
然后創建一個過程,在每個月的最后一天填充MyTable2
create or replace procedure pr_populate_Mytable2 is
begin
insert into MyTable2
select myColumn1, myColumn2
from MyTable
where to_char(myColumn_DATE, 'YYYY/MM') = to_char(sysdate,'YYYY/MM');
commit;
end;
通過從dbms_scheduler
調用該過程作為
declare
v_job_name varchar2(32) := 'jb_populate_Mytable2';
begin
dbms_scheduler.create_job(
job_name => v_job_name,
job_type => 'STORED_PROCEDURE',
job_action => 'pr_populate_Mytable2',
start_date => to_date('31-12-2018 20:00:00', 'dd-mm-yyyy hh24:mi:ss'),
repeat_interval => 'FREQ=MONTHLY; BYMONTHDAY=-1; BYHOUR=21;',
auto_drop => false,
comments => 'Populates our table on the last day of every month at 21 o''clock ');
dbms_scheduler.enable(v_job_name);
end;
從12月的最后一天晚上8點開始,並在將來的每個月的最后幾天重復播放。
您可以使用CONNECT BY LEVEL <=
技巧生成行,然后使用日期函數的組合生成相關日期。
--Months for the current year.
select add_months(trunc(sysdate, 'year'), level-1) the_month
from dual
connect by level <= 12;
THE_MONTH
---------
2019-01-01
2019-02-01
2019-03-01
2019-04-01
2019-05-01
2019-06-01
2019-07-01
2019-08-01
2019-09-01
2019-10-01
2019-11-01
2019-12-01
然后使用該查詢創建內聯視圖,並將其連接到主表:
select *
from
(
--Months for the current year.
select add_months(trunc(sysdate, 'year'), level-1) the_month
from dual
connect by level <= 12
) months
left join mytable
on months.the_month = trunc(mycolumn_date, 'month');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.