2017-07-31 74 views
2

我有这样的主表:SQL服务器 - 如何值映射到主表

tblMain 
----------------------------------------------- 
|ClientNo|Country1|Country2|Country3|Agreement| 
|--------+--------+--------+--------+---------| 
|111123 |SG  |TH  |PH  |OA1  | 
|111222 |PH  |MY  |JP  |OA2  | 
|323211 |MY  |SG  |PH  |OA3  | 
----------------------------------------------- 

和我有这些映射表:

tblCountry 
------------------------- 
|CountryCode|CountryName| 
|-----------+-----------| 
|SG   |Singapore | 
|MY   |Malaysia | 
|PH   |Philippines| 
|TH   |Thailand | 
|JP   |Japan  | 
------------------------- 

tblAgreement 
-------------------- 
|ACode|ADescription| 
|-----+------------| 
|OA1 |Agreement1 | 
|OA2 |Agreement2 | 
|OA3 |Agreement3 | 
-------------------- 

我需要实现的是刚刚返回主表而不是代码,我需要映射的名称/描述。 所以在我的例子,它应该是这样的:

------------------------------------------------------- 
|ClientNo|Country1 |Country2 |Country3 |Agreement | 
|--------+-----------+---------+-----------+--------- | 
|111123 |Singapore |Thailand |Philippines|Agreement1| 
|111222 |Philippines|Malaysia |Japan  |Agreement2| 
|323211 |Malaysia |Singapore|Philippines|Agreement3| 
------------------------------------------------------- 

能否请您帮助我如何解决这个问题?提前谢谢

+0

你能合并三张表吗?并获得一个表的输出。 –

+0

你需要什么? –

回答

10

它在select语句中使用连接而不是子查询是很好的。请参阅下面的解决方案。

Select 
    Main.ClientNo As ClientNo, 
    CountryA.CountryName, 
    CountryB.CountryName, 
    CountryC.CountryName, 
    A.ADescription As Aggrement 
From tblMain AS Main 
INNER JOIN tblCountry AS CountryA ON CountryA.CountryCode = Main.Country1 
INNER JOIN tblCountry AS CountryB ON CountryB.CountryCode = Main.Country2 
INNER JOIN tblCountry AS CountryC ON CountryC.CountryCode = Main.Country3 
INNER JOIN tblAgreement A ON Main.Agreement = A.Acode; 
1
Select 
    Main.ClientNum As ClientNo, 
    (Select CountryName From tblCountry Where CountryCode = Main.Country1) As Country1, 
    (Select CountryName From tblCountry Where CountryCode = Main.Country2) As Country2, 
    (Select CountryName From tblCountry Where CountryCode = Main.Country3) As Country3, 
    A.Adescrition As Aggrement 
From tblMain Main 
Inner Join tblAgreement A 
On Main.Aggrement = A.Acode;