My question is similar to SQL select Group query. But there is change in schema and I want different result as mentioned below. the solutions of given link doesn't give me the proper solutions. You can use SQL fiddle to solve this.
Below is my Table
Table1
+--------+----------+---------+
| 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 |
+--------+----------+---------+
Now I want to display the two lowest amount for each product and if the amount is same then anyone according to ascending alphabet order of make column...
So I want to build single SQL query which gives me result as below..
+--------+----------+---------+
| amount | make | product |
+--------+----------+---------+
| 100 | Nokia | Mobiles |
| 300 | Lava | Mobiles |
| 100 | Floyer | Gift |
| 300 | Feeling | Gift |
+--------+----------+---------+
Kindly help me to build such query..
This should help you ..
First one had a bug, it is updated now.
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
Have fun with it and with the fiddler : http://sqlfiddle.com/#!2/bdd1a/115/0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With