sql查询按过滤器计算记录

时间:2015-04-08 11:41:56

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

我有这个问题:

 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。 / p>

在图像示例中,另外两列应该包含如下数据:

1 | 1

3 | 1

1 | 0

3 | 1

3 | 1

1 个答案:

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