Created
February 29, 2024 21:06
-
-
Save mikehins/85a8be3e6535b6a694c9c59335471e1a to your computer and use it in GitHub Desktop.
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
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