最大的SQL查询

时间:2014-11-20 20:16:39

标签: sql sql-server database

SELECT  MATCH_ID ,
        PLAYER_ID ,
        COUNT(PLAYER_ID) AS TOTAL
FROM    MATCH_RESULTS
GROUP BY MATCH_ID ,
        PLAYER_ID

我想知道哪位球员在比赛中打得更多 我想使用MAX(COUNT(PLAYER_ID)),但它不允许我。 有人可以考虑一个答案吗?

5 个答案:

答案 0 :(得分:0)

如果你只想要哪个玩家拥有最多匹配的ID,你可以使用:

SELECT  PLAYER_ID ,
        COUNT(PLAYER_ID) AS MatchCount
FROM    MATCH_RESULTS
GROUP BY PLAYER_ID

答案 1 :(得分:0)

这是一个更新的答案,它将返回所有玩家所玩的最高匹配数:

http://sqlfiddle.com/#!6/16586/9

;with cte as (
  SELECT player_id, count(1) as matchesPlayed
  from match_results
  group by player_id
)
select *
from cte
where matchesPlayed = (select max(matchesPlayed) from cte)

上述方法称为公用表表达式 http://msdn.microsoft.com/en-us/library/ms175972.aspx

也有很多其他方法可以达到结果。

答案 2 :(得分:0)

你可以试试这个:

SELECT TOP 1
    MATCH_ID,
    PLAYER_ID,
    COUNT(*)
FROM MATCH_RESULTS
GROUP BY MATCH_ID,PLAYER_ID
ORDER BY COUNT(*) DESC

答案 3 :(得分:-1)

如果你只想要顶级玩家,试试这个:

SELECT PLAYER_ID, COUNT(1) AS TOTAL 
FROM MATCH_RESULTS 
GROUP BY PLAYER_ID
ORDER BY COUNT(1) DESC
LIMIT 1

答案 4 :(得分:-1)

您必须选择最多作为第一个结果:

SELECT PLAYER_ID, COUNT(*) as TOTAL
FROM MATCH_RESULTS 
GROUP BY PLAYER_ID
ORDER BY TOTAL DESC

http://sqlfiddle.com/#!6/4e300/3