2014-10-27 460 views
0

我有以下腳本,顯示從SYSDATE過去的11個月〜的Oracle SQL(Oracle11g中) - select語句哪裏日期等於另一個select語句

select * from (
select level-1 as num, 
to_char(add_months(trunc(sysdate,'MM'),- (level-1)),'MM')||'-'||to_char(add_months(trunc(sysdate,'MM'),- (level-1)),'YYYY') as dte 
from dual 
connect by level <= 12 
) 
pivot (
max(dte) as "DATE" 
for num in (0 as "CURRENT", 1 as "1", 2 as "2", 3 as "3", 4 as "4", 5 as "5",6 as "6",7 as "7",8 as "8",9 as "9",10 as "10", 11 as "11")) 

enter image description here

我想創建一個表格,其中顯示交貨日期('MM-YYYY')等於上述腳本生成的日期的交貨數量。

我得到的交貨數量和交貨日期從以下

select dp.catnr, 
     nvl(sum(dp.del_qty),0) del_qty 
    from [email protected]_to_cdsuk dh, 
     [email protected]_to_cdsuk dp 
where dp.dhead_no = dh.dhead_no 
    and dh.d_status = '9' 
    and dp.article_no = 9||'2EDVD0007' 
    and to_char(trunc(dh.actshpdate),'MM')||'-'||to_char(trunc(dh.actshpdate),'YYYY') = = --this is where I would like to match the result of the above script 
     group by dp.catnr 

結果看起來是這樣的......

enter image description here

任何想法,將不勝感激。

感謝,SMORF

回答

1
with date_series as (
    select add_months(trunc(sysdate,'MM'), 1 - lvl) start_date, 
     add_months(trunc(sysdate,'MM'), 2-lvl) - 1/24/60/60 end_date 
    from (select level lvl from dual connect by level <= 12) 
), 
your_table as (
    select 'catnr1' catnr, 100500 del_qty, sysdate actshpdate from dual 
    union all select 'catnr1' catnr, 10 del_qty, sysdate-30 actshpdate from dual 
    union all select 'catnr2' catnr, 15 del_qty, sysdate-60 actshpdate from dual 
), 
subquery as (
select to_char(ds.start_date, 'MM-YYYY') dte, t.catnr, sum(nvl(t.del_qty, 0)) del_qty 
from date_series ds left join your_table t 
    on (t.actshpdate between ds.start_date and ds.end_date) 
group by to_char(ds.start_date, 'MM-YYYY'), t.catnr  
)  
select * from subquery pivot (sum(del_qty) s for dte in ('11-2013' d1, '12-2013' d2, '08-2014' d10, '09-2014' d11, '10-2014' d12)) 
where catnr is not null;