Skip to content

Instantly share code, notes, and snippets.

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 Skrip42/d132f56b1fd8c6689fea97ce19c87cd0 to your computer and use it in GitHub Desktop.
Save Skrip42/d132f56b1fd8c6689fea97ce19c87cd0 to your computer and use it in GitHub Desktop.
MySQL Select top n for each group
set @num := 0, @type := '';
select type, variety, price
from (
select type, variety, price,
@num := if(@type = type, @num + 1, 1) as row_number,
@type := type as dummy
from fruits
order by type, price
) as x where x.row_number <= 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment