下面是我的 table
表格1
+--------+----------+---------+
| amount | make | product |
+--------+----------+---------+
| 100 | Nokia | Mobiles |
| 300 | Samesung | Mobiles |
| 700 | Micromax | Mobiles |
| 1000 | Karbonn | Mobiles |
| 500 | Lava | Mobiles |
| 100 | Floyer | Gift |
| 500 | Arichies | Gift |
| 300 | Feeling | Gift |
+--------+----------+---------+
现在,我要显示每种产品的两个最高金额...
所以我想建立一个单一的SQL查询,它给我的结果如下..
+--------+----------+---------+
| amount | make | product |
+--------+----------+---------+
| 1000 | Karbonn | Mobiles |
| 700 | Micromax | Mobiles |
| 500 | Arichies | Gift |
| 300 | Feeling | Gift |
+--------+----------+---------+
请帮助我建立这样的查询..
最佳答案
您可以使用此解决方案根据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
只需将
2
更改为您希望每种产品检索的头几行即可。如果要检索每个产品的最低两行,则只需将
<=
中的INNER JOIN
符号更改为>=
即可。您可以在这里摆弄这个解决方案:SQL-Fiddle Demo