在选择排名中选择

时间:2019-01-31 13:36:53

标签: mysql sql

有人可以指出我该如何从结果查询中选择特定的用户名及其排名吗?我正在尝试检索FoxDown的排名。

我相信我需要以某种方式Select username, my_rank (Select....从该查询中进行选择。

当前查询

    SELECT
    username,
    SUM(goals) as Diff,
    RANK() OVER (ORDER BY Diff DESC) my_rank
    FROM results
    WHERE Week = 'Week 23'
    GROUP by username
    ORDER by my_rank

查询结果表

username  Diff  my_rank
Sugar      12     1
Coj        10     2
Gunners     8     3
Captain     6     4
Spoon       6     4
Ric         6     4
FoxDown     6     4
shau        4     8
Josh        4     8
nol         4     8
pesty       4     8
Hill        4     8
Jg          4     8

2 个答案:

答案 0 :(得分:1)

Window functions are calculated after the where clause, logically。因此,您必须将窗口函数计算嵌套在派生表中,然后对其进行过滤:

SELECT *
FROM (
  SELECT
    username,
    SUM(goals) as Diff,
    RANK() OVER (ORDER BY SUM(goals) DESC) my_rank
  FROM results
  WHERE Week = 'Week 23'
  GROUP by username
) t
WHERE username = 'FoxDown'

请注意,您无法引用同一SELECT级别的列别名,因此需要在排名计算中重复使用SUM(goals)聚合函数。之所以再次起作用,是因为合计函数在窗口函数之前 逻辑上计算(请参见同一链接的博客文章)

答案 1 :(得分:1)

这有效!!

WITH players_results AS(
    SELECT
        username,
        SUM(goals) as Diff,
        RANK() OVER (    
            ORDER BY Diff DESC      
        ) my_rank
    FROM
        players_results
        WHERE matchweek = 'Matchweek 24'
        GROUP by username
        ORDER by my_rank
    )
    SELECT 
        * 
    FROM 
        players_results
    WHERE 
        username = 'FoxDown'