SQL Left Join Query以获取更多列

时间:2017-04-11 11:52:33

标签: sql

我希望加入以下两个表格

Table_1_CODE

Code    Desc
LC01    Karachi
LC02    Hyderabad
DP01    Account
DP02    Marketing
SH01    Night
SH02    Day


Table_2_DETAILS 

Col_1   Col_2   Col_3   Col_4
Mumtaz  LC01    DP02    SH01
Sajid   LC02    DP01    SH02
Imtiaz  LC01    DP02    SH02

我要找的输出是

Name    Loc        Dept       Shift
Mumtaz  Karachi    Marketing  Night
Sajid   Hyderabad  Account    Day
Imtiaz  Karachi    Marketing  Day

我希望使用SQL

来做到这一点

2 个答案:

答案 0 :(得分:0)

尝试以下查询:

SELECT col_1, t11.description, t12.description, t13.description
FROM Table_2_DETAILS t2 INNER JOIN Table_1_Code t11 
ON t11.code = t2.Col_2 
INNER JOIN Table_1_Code t12
ON t12.code = t2.col_3
INNER JOIN Table_1_Code t13
ON t13.code = t2.col_4;

我还没有运行查询,所以如果有任何问题请发表评论。

答案 1 :(得分:0)

这就是你想要的。您必须在不同的列上多次连接表1。

SELECT Col_1 AS 'Name',a.[Desc] AS 'Loc',b.[Desc] AS 'Dept',c.[Desc] AS 
'Shift'
FROM Table_2
   JOIN Table_1 a ON Table_2.Col_2 = a.Code
   JOIN Table_1 b ON Table_2.Col_3 = b.Code
   JOIN Table_1 c ON Table_2.Col_4 = c.Code 

ORDER BY c.[Desc] DESC
GO