-5

我需要找到总 AST 最多的前 5 名球员

期望的结果:

PlayerID   Sum(AST)  
3           10  
1           6  
2           5  

我的两张桌子:

tblPlayers   
PlayerID  
1  
2  
3  
4  
5  


tblIndStats  
GameID PlayerID AST  
1       2        2  
2       2        4  
3       3        5  
4       3        5
4

4 回答 4

2

This should get you top 5 in Microsoft SQL Server:

select top 5 PlayerID, sum(AST) as SumAST
from tblIndStats
group by PlayerID
order by SumAST desc --, PlayerID

Running example: Here's a SQL Fiddle showing results. Example shows the top 5, top 5 extended as well as all results for reference.

A different problem - several players on fifth place

But there's a different question here as well. What if your last (fifth) record is shared among several players? Say that 3 of them have the same AST sum. Which one would you include in the result then? My example fiddle data shows such a scenario as there are three players that all have SumAST = 3.

WITH TIES to the rescue

For such cases you can use with ties in SQL Server that will automatically include all records that match last place so you wouldn't forget about any player that should as well be honoured (fair play baby). ;)

select top 5 with ties PlayerID, sum(AST) as SumAST
from tblIndStats
group by PlayerID
order by SumAST desc
于 2013-01-24T12:55:13.087 回答
2

对于 Sql 服务器

SELECT TOP 5
    PlayerID, SUM(AST) ASTSUM
FROM tblIndStats
GROUP BY PlayerID
ORDER BY ASTSUM DESC
于 2013-01-24T12:54:21.887 回答
0

甲骨文:

SELECT *
    FROM (
            SELECT PlayerId, SUM(AST)
              FROM tblIndStats S
          GROUP BY PlayerId
          ORDER BY SUM(AST) DESC
          )
    WHERE ROWNUM <= 5

SQL 服务器:

SELECT TOP(5) *
    FROM (
            SELECT PlayerId, SUM(AST)
              FROM tblIndStats S
          GROUP BY PlayerId
          ORDER BY SUM(AST) DESC
          )

我的 SQL:

SELECT *
    FROM (
            SELECT PlayerId, SUM(AST)
              FROM tblIndStats S
          GROUP BY PlayerId
          ORDER BY SUM(AST) DESC
          )
   LIMIT 5
于 2013-01-24T12:54:19.173 回答
-1

(顶级构造类型可能是特定于数据库的)

select playerID, sum(AST)
from tblIndStats
group by playerID
order by sum(AST) desc

您不显示 tblPlayers 中的任何其他列,因此不确定您想要从该表中获得什么。

于 2013-01-24T12:53:31.393 回答