Skip to content

Instantly share code, notes, and snippets.

@kkempin
Created June 20, 2017 03:31
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 kkempin/148e3ac431307a1881cb060d6eceed4c to your computer and use it in GitHub Desktop.
Save kkempin/148e3ac431307a1881cb060d6eceed4c to your computer and use it in GitHub Desktop.
blog_lateral_join
SELECT user_id, first_order_time, next_order_time, id FROM
(SELECT user_id, min(created_at) AS first_order_time FROM orders GROUP BY user_id) o1
LEFT JOIN LATERAL
(SELECT id, created_at AS next_order_time
FROM orders
WHERE user_id = o1.user_id AND created_at > o1.first_order_time
ORDER BY created_at ASC LIMIT 1)
o2 ON true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment