基于记录计数的动态交叉表

时间:2015-11-13 20:41:08

标签: sql sql-server

我有一个表“联系人”与

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

psuedo 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

有些大师可以帮助我这样做吗?

1 个答案:

答案 0 :(得分: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;