I am trying to include non-aggregated data, e.g. user_id
after applying an aggregated function that does not include that same data.
I have found a solutions and looking for a more elegant solution.
I am looking for a solution without using a window function (like row_number
).
Here is my data: It represent an event of a competition. Every unique combination of event_date and tier is a unique competition. My goal is to get the winner of each competition.
CREATE TABLE interview_2
(
user_id INT,
tier VARCHAR(25),
event_date DATE,
user_score INT
);
INSERT INTO interview_2 VALUES ( 1, 'A', GETDATE(), 100 );
INSERT INTO interview_2 VALUES ( 2, 'B', GETDATE(), 80);
INSERT INTO interview_2 VALUES ( 1, 'A', DATEADD( DAY, 1, GETDATE() ), 90);
INSERT INTO interview_2 VALUES ( 3, 'A', DATEADD( DAY, 1, GETDATE() ), 110);
INSERT INTO interview_2 VALUES ( 4, 'A', GETDATE(), 60);
INSERT INTO interview_2 VALUES ( 5, 'B', GETDATE(), 50);
GO
My solution was a simple join:
SELECT scores.tier,
scores.event_date,
users.user_id,
scores.max_score
FROM
interview_2 users
JOIN
(SELECT
tier,
event_date,
MAX(user_score) AS 'max_score'
FROM
interview_2 scores
GROUP BY
tier, event_date) scores ON users.tier = scores.tier
AND users.event_date = scores.event_date
AND users.user_score = scores.max_score
ORDER BY
1, 2, 4;
Output:
tier event_date user_id user_score
--------------------------------------
A 2022-03-18 1 100
A 2022-03-19 3 110
B 2022-03-18 2 80
Is there a simpler solution?