2015-04-08 280 views
0

數記錄我有這個疑問:SQL查詢通過過濾

SELECT [ScheduleId] 
     ,[EventId] 
     ,s.[SkillId] 
     ,[ADEmployeeId] 
     ,sk.[Description] 
    FROM [Schedule] s 
    INNER JOIN [Skills] sk 
    ON s.SkillId = sk.SkillId 
    WHERE EventId = 1 

這是輸出:

enter image description here

我想有另一列這將爲每個描述怎麼說很多位置都可用(將計算具有相同描述的行),還有一列將計算具有相同描述的行數ADEmployeeID。

在圖像的例子中,兩個附加列應具有這樣的數據:

1 | 1

3 | 1

1 | 0

3 | 1

3 | 1

回答

6

你想窗口功能:

SELECT [ScheduleId],[EventId], s.[SkillId], [ADEmployeeId], sk.[Description], 
     COUNT(*) OVER (PARTITION BY sk.Description) as col1, 
     COUNT(ADEmployeeId) OVER (PARTITION BY sk.Description) as col2 
FROM [Schedule] s INNER JOIN 
    [Skills] sk 
    ON s.SkillId = sk.SkillId 
WHERE EventId = 1;