Forked from erichnascimento/first-row-each-group.sql
Created
October 16, 2016 16:34
-
-
Save hibellm/b0413e42a36ac3942bd41def68962cb0 to your computer and use it in GitHub Desktop.
Select first row in each GROUP BYgroup
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
/* | |
On Oracle 8i+, SQL Server 2005+, PostgreSQL 8.4+, DB2, Firebird 2.1+, Teradata, Sybase, Vertica: | |
*/ | |
WITH summary AS ( | |
SELECT p.id, | |
p.customer, | |
p.total, | |
ROW_NUMBER() OVER(PARTITION BY p.customer | |
ORDER BY p.total DESC) AS rk | |
FROM PURCHASES p) | |
SELECT s.* | |
FROM summary s | |
WHERE s.rk = 1; | |
/* | |
Supported by any database: | |
But you need to add logic to break ties | |
*/ | |
SELECT MIN(x.id), -- change to MAX if you want the highest | |
x.customer, | |
x.total | |
FROM PURCHASES x | |
JOIN (SELECT p.customer, | |
MAX(total) AS max_total | |
FROM PURCHASES p | |
GROUP BY p.customer) y ON y.customer = x.customer | |
AND y.max_total = x.total | |
GROUP BY x.customer, x.total | |
-- Reference: http://stackoverflow.com/a/3800572 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment