如何获取每年的积分名称和最大值? (SQL) [重复]

Posted

技术标签:

【中文标题】如何获取每年的积分名称和最大值? (SQL) [重复]【英文标题】:How to get the name and maximum values of points for each year? (SQL) [duplicate] 【发布时间】:2021-11-13 07:59:16 【问题描述】:

这是我目前的代码,它在 T-SQL 中。

我无法添加 driver_name 列。我应该使用什么样的聚合?

SELECT MAX(race_points) max_points, year, driver_name
FROM 

    (SELECT

        CONCAT(forename,' ',surname) AS driver_name,
        year,
        (CONVERT(FLOAT,points)) AS race_points     
     
    FROM 
            results AS r

            INNER JOIN constructors AS c
            ON r.constructorId = c.constructorId

            INNER JOIN drivers AS d
            ON r.driverId = d.driverId

            INNER JOIN races AS rc
            ON r.raceId = rc.raceId) AS sub
GROUP BY year;

这就是 sub 的样子

driver_name year race_points
a 2010 2
a 2011 3
b 2011 4
b 2012 3
c 2012 4

我试图让它看起来像谎言

driver_name year max_points
a 2010 2
b 2011 4
c 2012 4

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

使用row_number(),您可以根据您对数字进行分区的方式为您的行编号。如果您对它进行相应的排序,您可以从每个组中选择第 1 行。

WITH cte as
(
   SELECT
     CONCAT(forename,' ',surname) AS driver_name,
     year,
     (CONVERT(FLOAT,points)) AS race_points,
     row_number() over (partition by year order by (CONVERT(FLOAT,points)) desc) as rn     
   FROM 
     results AS r    
     INNER JOIN constructors AS c ON r.constructorId = c.constructorId
     INNER JOIN drivers AS d ON r.driverId = d.driverId
     INNER JOIN races AS rc ON r.raceId = rc.raceId
)
SELECT * FROM cte 
WHERE rn = 1

【讨论】:

以上是关于如何获取每年的积分名称和最大值? (SQL) [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何按一列的最大值获取SQL行,按另一列分组

sql中如何取重复的数据取时间最近的一条?

Spark SQL - 查找每年一个月的最大值

3.8上午

T-Sql 每年获取员工开始和结束日期

python调用tushare获取沪深A股票资金流向数据