-
-
Save kwd/3149547 to your computer and use it in GitHub Desktop.
MYSQL: Select min/max row from each category
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
SOURCE: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ | |
+--------+------------+-------+ | |
| type | variety | price | | |
+--------+------------+-------+ | |
| apple | gala | 2.79 | | |
| apple | fuji | 0.24 | | |
| apple | limbertwig | 2.87 | | |
| orange | valencia | 3.59 | | |
| orange | navel | 9.36 | | |
| pear | bradford | 6.05 | | |
| pear | bartlett | 2.14 | | |
| cherry | bing | 2.55 | | |
| cherry | chelan | 6.33 | | |
+--------+------------+-------+ | |
select f.type, f.variety, f.price | |
from ( | |
select type, min(price) as minprice | |
from fruits group by type | |
) as x inner join fruits as f on f.type = x.type and f.price = x.minprice; | |
+--------+----------+-------+ | |
| type | variety | price | | |
+--------+----------+-------+ | |
| apple | fuji | 0.24 | | |
| cherry | bing | 2.55 | | |
| orange | valencia | 3.59 | | |
| pear | bartlett | 2.14 | | |
+--------+----------+-------+ | |
-- This is what the inner request returns -- | |
select type, min(price) as minprice | |
from fruits | |
group by type; | |
+--------+----------+ | |
| type | minprice | | |
+--------+----------+ | |
| apple | 0.24 | | |
| cherry | 2.55 | | |
| orange | 3.59 | | |
| pear | 2.14 | | |
+--------+----------+ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment