i have some rows on "MENU" table
id, shop, size
1, 1 , 3
2, 1 , 8
3, 2 , 5
i need to show 1 row for each shop so if shop id is same then show the row with high value on column size
and results should be like this
id, shop, size
2, 1 , 8
3, 2 , 5
also if size is 0 on both rows it will display just 1 row
i need something like this
SELECT * FROM menu GROUP by shop
but to show the row with high value
i have tried this but if rows have 0 on column size then it shows both of them
SELECT a.* FROM menu a
LEFT JOIN menu b
ON a.shop=b.shop AND a.size< b.size
WHERE b.size NULL
2
Answers
Provided you’re using a recent version of MySql that supports window functions this is typically resolved with row_number:
The most typical way to solve such tasks is with
ROW_NUMBER
,RANK
orDENSE_RANK
as shown in Stu’s answer.Another option: Get the maximum size per shop, then use this result to retrieve the rows:
Another option: select rows for which no row with the same shop but a higher size exists: