2013-12-11 83 views
0

有兩個表,我必須參加,併產生預期的結果加入一個表的兩個表顯示的列行

EMPLOYEE表

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

EmployeeNationality表

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(亞當)有三條記錄,但我總是必須只顯示兩個國籍,所以列的數目是固定的。 在此先感謝

+1

['PIVOT'](http://technet.microsoft.com/en-us/library/ms177410(v = sql.105).aspx) –

+0

因此,如果一個「有」三個國籍,你想省略持續?哪一個? –

+0

截至目前,這不是一個問題,我可以省略任何,但我更願意省略第一個 – Swamy

回答

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