Created
March 8, 2023 15:51
-
-
Save mikepaszkiewicz/b8759fab46b23c3964192047cbd5cac5 to your computer and use it in GitHub Desktop.
join users with their latest device by created_at
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
u.*, | |
row_to_json(d.*) device | |
FROM | |
users u | |
INNER JOIN ( | |
SELECT | |
user_id, | |
MAX(created_at) MaxDate | |
FROM | |
devices | |
GROUP BY | |
user_id) MaxDates ON u.id = MaxDates.user_id | |
LEFT OUTER JOIN devices d ON MaxDates.user_id = d.user_id | |
AND MaxDates.MaxDate = d.created_at |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment