← 返回 amazon 的题目列表SQL: Window Function to Rank Within Group
类型:online_judge
Given events(user_id INT, event_time TIMESTAMP, event_type STRING, revenue DECIMAL(10,2)), write an SQL query to find each user's most recent event. Output:
user_id
event_time
event_type
revenue
Requirements:
If multiple events share the same timestamp for a user, pick the one with higher revenue as the most recent.
Use a window function such as ROW_NUMBER().
Data scale: up to 100M rows.
Validation cases:
Multiple events per user -> pick max event_time
Same event_time -> pick max revenue
Multiple users -> one row per user
revenue may be NULL -> treat NULL as smallest
Example
Input
events:
(1,'2025-01-01 10:00:00','click',NULL)
(1,'2025-01-01 11:00:00','purchase',20.0)
(2,'2025-01-01 09:00:00','click',0.0)
Output
1 2025-01-01 11:00:00 purchase 20.0
2 2025-01-01 09:00:00 click 0.0