This is my code so far. It's in T-SQL.
However, it only selects the item with max values for each year instead of the total points.
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
This is how sub looks like
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 |
I'm trying to make it look like this
driver_name | year | max_points |
---|---|---|
b | 2011 | 4 |
d | 2012 | 8 |
What I'm currently getting is this
driver_name | year | max_points |
---|---|---|
b | 2011 | 2 |
d | 2012 | 4 |
Any help would be really appreciated.
CodePudding user response:
You want aggregation with the window functions:
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;