如何获取每年的积分名称和最大总和值?
Posted
技术标签:
【中文标题】如何获取每年的积分名称和最大总和值?【英文标题】:How to get the name and maximum sum values of points for each year? 【发布时间】:2021-11-15 00:48:17 【问题描述】:到目前为止,这是我的代码。它在 T-SQL 中。
但是,它只选择每年具有最大值的项目,而不是总分。
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
这就是 sub 的样子
driver_name | year | race_points |
---|---|---|
a | 2011 | 1 |
a | 2011 | 1 |
b | 2011 | 2 |
b | 2011 | 2 |
c | 2012 | 3 |
c | 2012 | 3 |
d | 2012 | 4 |
d | 2012 | 4 |
我试图让它看起来像这样
driver_name | year | max_points |
---|---|---|
b | 2011 | 4 |
d | 2012 | 8 |
我目前得到的是这个
driver_name | year | max_points |
---|---|---|
b | 2011 | 2 |
d | 2012 | 4 |
任何帮助将不胜感激。
【问题讨论】:
您没有在 CTE 中汇总您的价值观;添加聚合,您就有了解决方案。 非常感谢 【参考方案1】:您希望使用窗口函数进行聚合:
WITH cte as (
SELECT CONCAT(forename, ' ', surname) AS driver_name,
year, SUM(points) as race_points,
RANK() OVER (PARTITION BY year ORDER BY SUM(points) DESC) as seqnum
FROM results r JOIN
constructors c
ON r.constructorId = c.constructorId JOIN
drivers d
ON r.driverId = d.driverId JOIN
races rc
ON r.raceId = rc.raceId
GROUP BY CONCAT(forename, ' ', surname), year
)
SELECT *
FROM cte
WHERE seqnum = 1;
【讨论】:
以上是关于如何获取每年的积分名称和最大总和值?的主要内容,如果未能解决你的问题,请参考以下文章
获取 3D numpy 数组中沿轴的连续非 nans 值总和的最大值