足球联赛表积分与SQL

时间:2014-11-27 18:57:52

标签: sql sql-server tsql

对许多人来说,也许是一张熟悉的桌子。足球联赛桌。 但是,在这个列表中有一个错误,排名4和5,完全相同,所以这些团队不应该排名第4和第5,而是第4和第4,然后排名应该继续6。

Ranking | Team | Points | Goals difference | Goals scored | Goals against
1         A      3        4                  4              0
2         B      3        3                  3              0 
3         C      3        1                  2              1
4         D      3        1                  1              0
5         E      3        1                  1              0
6         F      1        0                  2              2 
7         G      1        0                  0              0 

我一直在尝试通过使用公用表表达式和SELECT ROW_Number来改进生成此表的MS SQL查询,但这从未给出正确的结果。有没有人有更好的主意?

2 个答案:

答案 0 :(得分:2)

您可以使用RANK()功能轻松完成此操作。

declare @table as table
(
    Team varchar(1),
    Points int,
    GoalsScored int,
    GoalsAgainst int
)

insert into @table values ('A', 3, 4, 0),
                          ('B', 3, 3, 0),
                          ('C', 3, 2, 1),
                          ('D', 3, 1, 0),
                          ('E', 3, 1, 0),
                          ('F', 1, 2, 2),
                          ('G', 1, 0, 0)

select RANK() OVER (ORDER BY points desc, GoalsScored - GoalsAgainst desc, GoalsScored desc) AS Rank   
      ,team
      ,points
      ,GoalsScored - GoalsAgainst as GoalsDifference
      ,GoalsScored
      ,GoalsAgainst
from @table
order by rank

答案 1 :(得分:0)

这是一个可能的解决方案。我不确定你的排名如何,所以我根据积分DESC,目标差异DESC,目标得分DESC和目标ASC排名。

;WITH

src AS (
    SELECT Team, Points, GoalsDiff, GoalsScor, GoalsAga
    FROM dbo.[stats]
)

,src2 AS (
    SELECT Points, GoalsDiff, GoalsScor, GoalsAga
    FROM src
    GROUP BY Points, GoalsDiff, GoalsScor, GoalsAga
)

,src3 AS (
SELECT ROW_NUMBER() OVER (ORDER BY Points DESC, GoalsDiff DESC, GoalsScor DESC, GoalsAga) AS Ranking
    ,Points, GoalsDiff, GoalsScor, GoalsAga
    FROM src2
)

SELECT src3.Ranking, src.Team, src.Points, src.GoalsDiff, src.GoalsScor, src.GoalsAga
FROM src
    INNER JOIN src3
        ON src.Points = src3.Points
        AND src.GoalsDiff = src3.GoalsDiff
        AND src.GoalsScor = src3.GoalsScor
        AND src.GoalsAga = src3.GoalsAga

我使用的基本方法是只选择统计数据本身,然后将它们全部分组。分组后,您可以对它们进行排名,然后加入分组统计数据,并将排名返回到原始数据,以获得针对团队的排名。想到这一点的一种方法是你对统计数据进行排名而不是对团队进行排名。

希望这有帮助。