一個小竅門,你可以做兩個步驟:rn
是row_number() over last_updated desc
,但調整時的item_no
計數爲小(1或2),這樣,當我們轉動,日期在排隊適當的專欄。然後像往常一樣PIVOT
。
with test_data (item_no, shipping_date, last_updated) as (
select 100, to_date('01-Sep-16','dd-mon-yy'), to_date('24-Aug-16','dd-mon-yy') from dual union all
select 101, to_date('10-Sep-16','dd-mon-yy'), to_date('24-Aug-16','dd-mon-yy') from dual union all
select 102, to_date('31-Aug-16','dd-mon-yy'), to_date('24-Aug-16','dd-mon-yy') from dual union all
select 101, to_date('11-Sep-16','dd-mon-yy'), to_date('25-Aug-16','dd-mon-yy') from dual union all
select 101, to_date('12-Sep-16','dd-mon-yy'), to_date('26-Aug-16','dd-mon-yy') from dual union all
select 100, to_date('31-Aug-16','dd-mon-yy'), to_date('27-Aug-16','dd-mon-yy') from dual union all
select 102, to_date('01-Sep-16','dd-mon-yy'), to_date('27-Aug-16','dd-mon-yy') from dual union all
select 103, to_date('01-Oct-16','dd-mon-yy'), to_date('27-Aug-16','dd-mon-yy') from dual
),
prep (item_no, shipping_date, last_updated, rn) as (
select item_no, shipping_date, last_updated,
row_number() over (partition by item_no order by last_updated desc)
+ greatest(0, 3 - count(*) over (partition by item_no))
from test_data
)
select item_no, "3_SHIPPING" as shipping_1, "3_UPDATED" as updated_1,
"2_SHIPPING" as shipping_2, "2_UPDATED" as updated_2,
"1_SHIPPING" as shipping_3, "1_UPDATED" as updated_3
from prep
pivot (
min(shipping_date) as shipping, min(last_updated) as updated for rn in (1, 2, 3)
)
order by item_no;
OUTPUT:
ITEM_NO SHIPPING_1 UPDATED_1 SHIPPING_2 UPDATED_2 SHIPPING_3 UPDATED_3
---------- ----------- ----------- ----------- ----------- ----------- -----------
100 01-SEP-2016 24-AUG-2016 31-AUG-2016 27-AUG-2016
101 10-SEP-2016 24-AUG-2016 11-SEP-2016 25-AUG-2016 12-SEP-2016 26-AUG-2016
102 31-AUG-2016 24-AUG-2016 01-SEP-2016 27-AUG-2016
103 01-OCT-2016 27-AUG-2016
幹得漂亮。爲了確切得到OP所要求的內容,我相信查詢需要使用'order by shipping_date asc'命令 - 雖然即使這樣也不適用於ITEM_NO 100. –
看起來像'LAST_UPDATED ASC'。對不起,我不小心 - 謝謝你指出。我會更新。 –
只需完成評論鏈:我需要在答案中添加另一個'ROW_NUMBER()',以分隔用於過濾最後3個事件的過濾器和用於排序列的過濾器。 –