Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikepaszkiewicz/b8759fab46b23c3964192047cbd5cac5 to your computer and use it in GitHub Desktop.
Save mikepaszkiewicz/b8759fab46b23c3964192047cbd5cac5 to your computer and use it in GitHub Desktop.
join users with their latest device by created_at
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