如何让MySQL返回与子查询绑定的排名?

时间:2017-07-06 19:53:00

标签: mysql sql

我试图创建一个图表,其中包含一些变量,用于绘制每年大学体育赛事的门票销售总额,以及它在数据库中存在的其他事件中的排名。我无法找到一种方法来使排名与每一行的每一年相对应。

这是我开始的地方:

SELECT
Year as year,
School,
`Ticket Sales`,
(SELECT 
    COUNT(School)+1 
    FROM schools 
    WHERE Year = 2016 AND `Ticket Sales` > (
        SELECT `Ticket Sales` 
            FROM schools 
            WHERE School = "College" AND Year = 2016)
        ) as Rank
FROM schools
WHERE School = "College"
ORDER BY Year DESC

以下是我的回复(注意它给出15 - 第一年的排名 - 每个例子):

Year    School  Ticket Sales Rank
2016    College 29054868    15
2015    College 29586555    15
2014    College 26928635    15
2013    College 25888524    15
2012    College 23432735    15
2011    College 26467598    15
2010    College 18395654    15
2009    College 20711850    15
2008    College 17107971    15
2007    College 17287093    15
2006    College 15351891    15
2005    College 12767307    15

编辑:要明确的是,每年排名下的数字应该不同。 2015年的排名与2016年不同,与2014年的排名不同等。

1 个答案:

答案 0 :(得分:0)

我相信这是你想要完成的事情:

SELECT Year,
       School,
       sum(`Ticket Sales`) as `Ticket Sales`,
       Count(*) as Rank
FROM schools
WHERE School = "College"
GROUP BY Year,
      School
ORDER BY Year DESC

请参阅示例结果here