Skip to content

Instantly share code, notes, and snippets.

@davidcrawford
Last active December 19, 2015 10:09
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 davidcrawford/5938827 to your computer and use it in GitHub Desktop.
Save davidcrawford/5938827 to your computer and use it in GitHub Desktop.
SELECT * FROM purchases ORDER BY created_at DESC;
id | customer_id | subtotal | shipping | tax | total | created_at
------+-------------+----------+----------+---------+----------+----------------------------
1101 | 83922 | 102.44 | 4.99 | 8.7074 | 116.1374 | 2013-07-05 22:49:09.20922
1051 | 83922 | 51.75 | 4.99 | 4.39875 | 61.13875 | 2013-07-05 22:48:45.353301
1079 | 48582 | 47.02 | 4.99 | 3.9967 | 56.0067 | 2013-07-05 22:48:02.866348
1057 | 48582 | 30.64 | 4.99 | 2.6 | 38.23 | 2013-07-05 22:47:12.535409
1048 | 48582 | 81.72 | 4.99 | 6.95 | 93.66 | 2013-07-05 22:46:18.304818
SELECT MAX(created_at) AS most_recent FROM purchases GROUP BY customer_id;
most_recent
----------------------------
2013-07-05 22:48:02.866348
2013-07-05 22:49:09.20922
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY created_at DESC
)
AS created_order
FROM purchases
id | customer_id | subtotal | shipping | tax | total | created_at | created_order
------+-------------+----------+----------+---------+----------+----------------------------+---------------
1079 | 48582 | 47.02 | 4.99 | 3.9967 | 56.0067 | 2013-07-05 22:48:02.866348 | 1
1057 | 48582 | 30.64 | 4.99 | 2.6 | 38.23 | 2013-07-05 22:47:12.535409 | 2
1048 | 48582 | 81.72 | 4.99 | 6.95 | 93.66 | 2013-07-05 22:46:18.304818 | 3
1101 | 83922 | 102.44 | 4.99 | 8.7074 | 116.1374 | 2013-07-05 22:49:09.20922 | 1
1051 | 83922 | 51.75 | 4.99 | 4.39875 | 61.13875 | 2013-07-05 22:48:45.353301 | 2
WITH ordered_purchases AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY created_at DESC
)
AS created_order
FROM purchases
)
SELECT * FROM ordered_purchases WHERE created_order = 1;
id | customer_id | subtotal | shipping | tax | total | created_at | created_order
------+-------------+----------+----------+--------+----------+----------------------------+---------------
1079 | 48582 | 47.02 | 4.99 | 3.9967 | 56.0067 | 2013-07-05 22:48:02.866348 | 1
1101 | 83922 | 102.44 | 4.99 | 8.7074 | 116.1374 | 2013-07-05 22:49:09.20922 | 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment