mah*_*esh 6 mysql sql database
我的问题类似于SQL select Group查询.但架构有变化,我想要不同的结果,如下所述.给定链接的解决方案并没有给我正确的解决方案.您可以使用SQL小提琴来解决此问题.
下面是我的表
表格1
+--------+----------+---------+
| amount | make | product |
+--------+----------+---------+
| 100 | Nokia | Mobiles |
| 300 | Samesung | Mobiles |
| 700 | Micromax | Mobiles |
| 1000 | Karbonn | Mobiles |
| 300 | Lava | Mobiles |
| 100 | Floyer | Gift |
| 500 | Arichies | Gift |
| 300 | Feeling | Gift |
+--------+----------+---------+
Run Code Online (Sandbox Code Playgroud)
现在我想显示每个产品的两个最低金额,如果金额相同,则根据make列的升序字母顺序排列任何人...
所以我想构建单个SQL查询,它给出了如下结果.
+--------+----------+---------+
| amount | make | product |
+--------+----------+---------+
| 100 | Nokia | Mobiles |
| 300 | Lava | Mobiles |
| 100 | Floyer | Gift |
| 300 | Feeling | Gift |
+--------+----------+---------+
Run Code Online (Sandbox Code Playgroud)
请帮我构建这样的查询..
这应该对你有帮助..
第一个有bug,现在已经更新了。
SELECT t.*
FROM (
SELECT @lim := 2,
@cg := ''
) vars,
(select * from Table1 order by product,amount, make) t
WHERE CASE WHEN @cg <> product THEN @r := @lim ELSE 1 END > 0
AND (@r := @r - 1) >= 0
AND (@cg := product) IS NOT NULL
ORDER BY
product,amount, make
Run Code Online (Sandbox Code Playgroud)
享受它和小提琴手的乐趣: http://sqlfiddle.com/#!2 /bdd1a/115/0