Skip to content

Instantly share code, notes, and snippets.

@mikehins
Created February 29, 2024 21:06
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 mikehins/85a8be3e6535b6a694c9c59335471e1a to your computer and use it in GitHub Desktop.
Save mikehins/85a8be3e6535b6a694c9c59335471e1a to your computer and use it in GitHub Desktop.
First Row of Many Similar Ones
SQL is a straightforward and expressive language, but it sometimes lacks constructs for writing queries in a simple way. It's more complicated than it should be to write a query to get, e.g., only the most expensive order for every customer of the current fiscal year. You can either use PostgreSQL's vendor-specific DISTINCT ON feature or window functions for every other database.
MySQL
SELECT *
FROM (
SELECT *, RANK() OVER(
PARTITION BY customer_id
ORDER BY price DESC
) AS _rank
FROM orders
WHERE year = 2024
) as _tmp
WHERE _rank = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment