2016-04-20 65 views
0

我有兩個表查詢連接兩個表和使用LISTAGG功能

 
price 
-------- 

id  value key 
sku1 r1  12 
sku1 r2  13 
sku2 r1  12 
sku3 r1  14 

specialprice 
----- 

id  value key startdate enddate 
sku2 r2  13 20-Mar  20-May 
sku3 r1  15 20-Mar  20-May 

我試圖用LISTAGG功能,並把像輸出:

 
output 
------ 
skuid value 
sku1 r1:12,r2:13 
sku2 r2:13 
sku3 r1:15 

如果在specialprice入口表和系統日期介於startdate和enddate之間,那麼我需要考慮,否則我需要從價格表中獲取價值。 在價格表中,一個id可能有兩個條目需要LISTAGG這兩條記錄。 特殊價格表可能沒有價格表中的ID條目。所以我用FULL OUTER JOIN

PFB查詢我構建:

SELECT 
    a.id, 
    listagg (a.value | | ':' | | nvl (a.key, ' '), ',') WITHIN GROUP (ORDER BY a.value) AS price 
FROM price a 
FULL OUTER JOIN specialprice b 
    ON(b.id = a.id) 
WHERE sysdate between b.startdate and b.enddate 
GROUP BY a.id 

,但問題是我不能夠得到加盟specialprice表值和關鍵。 請幫忙。

回答

0
SELECT a.id,listagg (a.value | | ':' | | nvl (a.key, ' '), ',') 
    WITHIN GROUP (ORDER BY a.value) AS price 
    FROM price a 
    LEFT OUTER JOIN specialprice b 
    ON(b.id = a.id and a.value = b.value and a.key = b.key) 
    WHERE (sysdate between b.startdate and b.enddate OR b.id IS NULL) 
    GROUP BY a.id 

根據要求解釋,如果b中有匹配的id,它必須是當前記錄。如果找不到匹配的記錄,則必須使用a的數據。左外連接應該足夠了。希望這可以幫助。

1

試試這個:

select id, listagg(value) within group(order by value) as price 
from (
select 
    p.id, 
    case when sp.id is not null and sysdate between sp.startdate and sp.enddate 
    then p.value||':'||p.key 
    else p.value||':'||p.key 
    end as value 
from price p 
left outer join specialprice sp 
    on p.id = sp.id 
) 
group by id;