2017-04-04 37 views
1

我遇到連接兩個表的實際問題。SQL - 在列值上連接兩個表=列名

我有這樣的主表:

---------------- 
|ID|Stock|Group| 
|--+-----+-----| 
|K3|US 11|1 | 
|K3|US 23|2 | 
|K3|HK 10|2 | 
|G5|SG 56|1 | 
|D1|PH 12|1 | 
|D1|UK 23|2 | 
---------------- 

,這映射表:

------------------------------------ 
|ID|Local1|Local2|Foreign1|Foreign2| 
|--+------+------+--------+--------| 
|K3|10 |20 |25  |30  | 
|G5|20 |30 |35  |40  | 
|D1|10 |15 |20  |50  | 
------------------------------------ 

我如何股票和組值的組合映射到我的映射表的列? 其中US=Local*others*=Foreign。 例如,第1組中的K3的股票US 11US 11表示市場是本地的。我如何從映射表中獲取Column Local1的值? 然後加入表作爲這樣的結果:

---------------------- 
|ID|Stock|Group|Ratio| 
|--+-----+-----+-----| 
|K3|US 11|1 |10 | 
|K3|US 23|2 |20 | 
|K3|HK 10|2 |30 | 
---------------------- 

我還沒有嘗試過任何東西,因爲我不知道該怎麼做。請幫忙。

回答

5

如果我理解正確的,下面應該是你所需要的:

Select 
    m.ID, 
    m.Stock, 
    m.[Group], 
    Case 
     when left(m.stock,2)='US' and m.[Group] =1 then mapping.Local1 
     when left(m.stock,2)='US' and m.[Group] =2 then mapping.Local2 
     when m.[Group]=1 then mapping.Foreign1 
     Else mapping.Foreign2 
    End as Ratio 
From 
    Main m 
    Join mapping on main.id = mapping.id 
+0

非常感謝你。這將完成這項工作。 – theo

2

您可以選擇使用外鍵

選擇main連接表。 idmainstockmaingroup,create_ratio_here from main left mappingmappingid = mainid其中mainid = K3

+0

感謝您的回覆,但我不認爲這會做這項工作。 – theo

1

你可以使用一個特定的選擇情況下,當設置你真正需要的地圖(但它是一個專門的解決方案)

select a.id,a.Stock, a.Group, 
     case when stock ='US 11' and group = 1 then b.Local1 
      when stock ='US 23' and group = 2 then b.Local2 
      when stock ='HK 10' and group = 2 then b.Foreign2 
      ..... 
    from main as a 
    inner join mapping as b on a.id=b.id 
+0

非常感謝你:) – theo