计算过程中出现的次数

时间:2014-09-25 17:09:36

标签: sql sql-server

我有一个过程,使用一些SELECTjoins条款,使用您的标准基本where语句输出行列表。

Employee        Value
--------------------------
Tommy Elliott   Damage
Tommy Elliott   Overage
Tommy Elliott   Damage
Tommy Elliott   Shortage
Tommy Elliott   Damage
Tommy Elliott   Shortage
Trevor Gray     Overage
Trevor Gray     Shortage
Trevor Gray     Overage
Trevor Gray     Shortage
Trevor Gray     Overage
Trevor Gray     Shortage

我想知道是否有人知道一个解决方案,我可以在这个下面添加一个新的SELECT语句,或者在同一个SELECT语句中能够:

  • 计算Tommy和Trevor出现的次数(根据上述数据,应为6次)

  • 并且对于Tommy和Trevor,计算他们有损伤,超额或短缺价值的次数。

我一直想弄明白而且不能。我确信这是COUNT的快速解决方案。

3 个答案:

答案 0 :(得分:0)

COUNT()的分析版可以将这些添加为列值保留您想要的详细信息。假设您的查询开头如下:

SELECT
  Employee,
  Value
FROM ... and the rest of your query

...添加如下计数:

SELECT
  Employee,
  Value,
  COUNT(*) OVER (PARTITION BY Employee) AS ThisEmpCount,
  COUNT(CASE WHEN Value = 'Damage' THEN 1 END)
    OVER (PARTITION BY Employee) AS ThisEmpDamageCount,
  COUNT(CASE WHEN Value = 'Outage' THEN 1 END)
    OVER (PARTITION BY Employee) AS ThisEmpOutageCount
FROM ... and the rest of your query

答案 1 :(得分:0)

select T.Employee, COUNT(T.Employee)
from 
(
  your query
)T
group by T.Employee

答案 2 :(得分:-1)

SELECT Employee, Value, Count(1) as No_Of_Times
FROM [Table]
GROUP BY Employee, Value
ORDER BY Employee, Value