将列添加到group by子句会扰乱计数

时间:2013-11-12 15:20:39

标签: sql sql-server

我需要计算列中重复项的数量,这样做完成后会这样:

SELECT CorrelationId, Count(CorrelationId) as total
FROM VoipDetailsView
WHERE ResponseCode = 200
GROUP BY CorrelationId

但是,当我尝试将其他列添加到结果

SELECT SessionIdTime, CorrelationId, Count(CorrelationId) as total
FROM VoipDetailsView
WHERE ResponseCode = 200
GROUP BY CorrelationId, SessionIdTime
ORDER BY SessionIdTime 

即使(或可能因为)现在显示重复值,所有计数现在都是0或1。我不介意重复,但我需要最后一列包含每个选定的重复CorrelationIds的总数。 (例如,如果值存在两次,则这两行的计数将为2)

我需要做什么样的查询?

3 个答案:

答案 0 :(得分:0)

SessionIdTime

min()列上使用聚合函数怎么样?
SELECT min(SessionIdTime), CorrelationId, Count(CorrelationId) as total
FROM VoipDetailsView
WHERE ResponseCode = 200
GROUP BY CorrelationId
ORDER BY min(SessionIdTime)

答案 1 :(得分:0)

您的第二个查询为您提供特定SessionIdTime中重复项CorrelationId的数量,这是您想要的吗? SessionIdTime是什么意思?

是的,你可以这样做:

SELECT CorrelationId, Count(*) as total
FROM VoipDetailsView
WHERE ResponseCode = 200
GROUP BY CorrelationId;

它有点优化

答案 2 :(得分:0)

您需要将CorrelationId的聚合分成单独的查询,并将其与您的表连接以获取其他列,例如:

SELECT v.SessionIdTime, v.CorrelationId, total
From VoipDetailsView v inner join
(SELECT CorrelationId, Count(CorrelationId) as total
FROM VoipDetailsView
WHERE ResponseCode = 200
GROUP BY CorrelationId) agg
on v.CorrelationId = agg.CorrelationId