2017-02-27 41 views
0

有人可以建議如何合併以下兩個結果集/表,以便實現預期輸出。將兩個表格合併爲相同列但選擇值不同

  • currentPrice值將優先從PriceChangedTable,如果不能從StatusChangedTable。空值是一個有效的值。

  • status值將優先從StatusChangedTable,並且如果不從PriceChangedTable

PriceChangedTable可用:

Id vehicle  currentPrice status 
    --------------------------------------------- 
    1 toyota  50000   Available 
    2 nisaan  null   Available 
    3 bmw   30000   Pending 

StatusChangedTable:從合併上述2

Id vehicle  currentPrice status 
    --------------------------------------------- 
    1 toyota  null   NotAvailable 
    3 bmw   40000   NotAvailable 
    4 dodge  50000   Pending 

輸出表:

Id vehicle  currentPrice status 
    --------------------------------------------- 
    1 toyota  50000   NotAvailable 
    2 nisaan  null   Available 
    3 bmw   30000   NotAvailable 
    4 dodge  50000   Pending 

請不要判斷表的設計技巧。

回答

0

這個查詢將返回預期輸出:

select 
    p.Id 
    ,p.vehicle 
    ,p.currentPrice 
    -- status value priority 1) StatusChangedTable, 2) PriceChangedTable 
    ,case when s.Id is not null then s.status else p.status end as status 
from PriceChangedTable p 
left join StatusChangedTable s on p.Id = s.Id 
union 
select 
    s.Id 
    ,s.vehicle 
    -- currentPrice value priority 1) PriceChangedTable, 2) StatusChangedTable 
    ,case when p.Id is not null then p.currentPrice else s.currentPrice end as currentPrice 
    ,s.status 
from StatusChangedTable s 
left join PriceChangedTable p on p.Id = s.Id 
0

嘗試與其他樣本數據,

SELECT isnull(pc.Id, sc.id) id 
    ,isnull(pc.vehicle, sc.vehicle) vehicle 
    ,isnull(pc.currentPrice, sc.currentPrice) currentPrice 
    ,isnull(sc.[status], pc.[status]) [status] 
FROM @PriceChnagedTable PC 
FULL OUTER JOIN @StatusChangedTable SC ON pc.id = sc.Id 
相關問題