Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select query help required

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..

like image 762
mahesh Avatar asked Sep 26 '12 06:09

mahesh


1 Answers

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

like image 111
Dumitrescu Bogdan Avatar answered Sep 20 '22 01:09

Dumitrescu Bogdan