加入两个表并将一个表的列显示为行

时间:2013-12-11 13:58:40

标签: sql-server-2008 sql-server-2008-r2

我必须加入两个表并产生预期的结果

员工表

EmpID   | EmpName
1       | Adam
2       | Eve
3       | John
4       | Steve

员工国籍表

EmpID   | Nationality
1       | US
1       | UK
1       | UKraine
2       | US
3       | Canada
4       | Spain

结果预期

EmpID   | EmpName   | Nationality1  | Nationality2 
1       | Adam      | US            | UK
2       | Eve       | US            | 
3       | John      | Canada        | 
4       | Steve     | Spain         | 

虽然员工ID 1(Adam)有三条记录,但我始终只需要显示两个国籍,因此列的数量是固定的。 提前致谢

1 个答案:

答案 0 :(得分:0)

如果您只需要两个国籍:

WITH CTE AS(
  SELECT e.EmpID, 
         e.EmpName, 
         en.Nationality,
         RN = ROW_NUMBER() OVER (PARTITION BY e.EmpID,e.EmpName
                                 ORDER BY e.EmpID)
  FROM   dbo.employee e 
         INNER JOIN employeenationality en 
                 ON e.empid = en.empid
)
SELECT DISTINCT c1.EmpID, c1.EmpName,
       Nationality1 = (SELECT Nationality FROM CTE Nationality1
                       WHERE c1.EmpID = Nationality1.EmpID
                       AND   Nationality1.RN = 1),
       Nationality2 = (SELECT Nationality FROM CTE Nationality2
                       WHERE c1.EmpID = Nationality2.EmpID
                       AND   Nationality2.RN = 2)
FROM CTE c1

Sql-Fiddle

否则使用PIVOT