sql server分组结果

时间:2011-11-24 10:57:30

标签: sql sql-server sql-server-2008

此查询返回它下面的列表,但是id会多次出现,我可以对id进行分组并将所有播放加起来,这样我就可以得到一个列表唯一ID,旁边有播放总数。这可能在sql?

SELECT [fkPlayerId],[plays]
FROM [dPlaysPerDay]
INNER JOIN dWinners
ON [dPlaysPerDay].[fkPlayerId]=dWinners.[pkWinnerId]

53693   1
53695   1
53696   1
53693   1
53692   2
53698   2
53697   1
53699   2
53698   3
53693   6
53699   2
53693   2
53700   2
53698   1

1 个答案:

答案 0 :(得分:6)

使用GROUP BY时,SELECT中的所有数据项都必须包含在GROUP BY中或放在Aggregate Function中。

因此,fkPlayerId应按分组,playsSUM()函数一起使用

SELECT [fkPlayerId], SUM([plays])
FROM [dPlaysPerDay]
INNER JOIN dWinners ON [dPlaysPerDay].[fkPlayerId]=dWinners.[pkWinnerId]
GROUP BY fkPlayerId

ORDER BY聚合函数,请为数据项指定别名,并按此顺序:

SELECT [fkPlayerId], SUM([plays]) as TotalPlays
FROM [dPlaysPerDay]
INNER JOIN dWinners ON [dPlaysPerDay].[fkPlayerId]=dWinners.[pkWinnerId]
GROUP BY fkPlayerId
ORDER BY TotalPlays