2017-04-13 78 views
0

因此,例如,我有這樣的表稱爲tb_ItemSQL服務器 - 如何選擇不同行,但在同一個表中的值

---------------------------------- 
|Item_Ref|Main_Item_Ref|Type|Rate| 
|--------+-------------+----+----| 
|1234ABC |MNJDH  |Sub |0 | 
|MNJDH |MNJDH  |Main|98 | 
---------------------------------- 

基本上,我要實現的是讓主的速率值項目並放在子項目上。

在此示例表中,如何能項目1234ABC得到其主要項目MNJDH 98率這樣返回行:

---------------------------------- 
|Item_Ref|Main_Item_Ref|Type|Rate| 
|--------+-------------+----+----| 
|1234ABC |MNJDH  |Sub |98 | 
---------------------------------- 

謝謝。

回答

1

您可以用自聯接做到這一點:

select i.*, m.Rate 
from tb_item i left join 
    tb_item m 
    on i.main_item_ref = m.main_item_ref and 
     m.type = 'Main' 
where i.type = 'Sub'; 
+0

非常感謝你的快速反應。我不知道雲可以加入同一張表:) – theo

1

自內加入

select t1.Item_Ref, t1.Main_Item_ref, t1.type,t2.Rate 
    from #temptable t1 
    inner join #temptable t2 
    on t1.Main_Item_ref = t2.Main_Item_ref 
    and t2.type = 'Main' 
    and t1.type ='Sub' 
+0

謝謝你的幫助:) – theo

相關問題