2015-11-13 76 views
0

我有一個表「人脈」與動態交叉的記錄數

EMPid ContactID EmergencyYN Priority 
--------------------------------------- 
10  20   Y   1 
10  39   N   1 
10  45   Y   2 
11  21   N   2 
12  20   Y   2 
12  25   Y   1 
12  33   Y   3 

我想什麼是結果集是

EmpID EmergencyContact1 EmergencyContact2 EmergencyContact3 
------------------------------------------------------------------ 
10  20     45 
11   
12  25     20     33 

僞SQL是接近我可以得到:

So n = max number of contacts where EmergencyYN =Y per empID 
Then build a string for x = 1 to N 
    @sql = @sql + 'EmergencyContact'+x 
next 

有些古茹能幫我做這個嗎?

+0

的可能的複製[SQL Server的動態PIVOT查詢?](http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) –

回答

0

我使用派生查詢來創建不同EmpID的列表。然後,對於每個返回的ID,我將查詢是否有匹配的緊急事件優先級。

SELECT 
    A.[EmpID] 
    ,(
     SELECT TOP 1 ContactID 
     FROM contacts B 
     WHERE B.EmpID=A.EmpID AND B.EmergencyYN='Y' AND B.[Priority]=1 
    ) AS [EmergencyContact1] 
    ,(
     SELECT TOP 1 ContactID 
     FROM contacts B 
     WHERE B.EmpID=A.EmpID AND B.EmergencyYN='Y' AND B.[Priority]=2 
    ) AS [EmergencyContact2] 
    ,(
     SELECT TOP 1 ContactID 
     FROM contacts B 
     WHERE B.EmpID=A.EmpID AND B.EmergencyYN='Y' AND B.[Priority]=3 
    ) AS [EmergencyContact3] 
FROM (
     SELECT DISTINCT EMPID 
     FROM contacts 
    ) AS A;