2017-02-27 63 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 
相关问题