SQL select group query

后端 未结 5 1067
萌比男神i
萌比男神i 2021-02-04 13:32

Below is my Table

Table1

+--------+----------+---------+  
| amount | make     | product |  
+--------+----------+---------+  
|    100 | Nokia    | Mo         


        
5条回答
  •  长情又很酷
    2021-02-04 14:14

    You can use this solution to retrieve the "group-wise maximum" based on the amount:

    SELECT a.*
    FROM Table1 a
    INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount
    GROUP BY a.amount, a.product
    HAVING COUNT(*) <= 2
    

    Simply change the 2 to however many of the top rows you want to retrieve per product.

    If you wanted to retrieve the lowest two rows per product, you can simply change the <= sign in the INNER JOIN to a >=.

    You can fiddle around with this solution here: SQL-Fiddle Demo

提交回复
热议问题