需要SQL select查询帮助

时间:2012-09-26 06:35:32

标签: mysql sql database

我的问题类似于SQL select Group query。但架构有变化,我想要不同的结果,如下所述。给定链接的解决方案并没有给我正确的解决方案。您可以使用SQL fiddle来解决此问题。

以下是我的表

表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    |   
+--------+----------+---------+  

现在我想显示每个产品的两个最低金额,如果金额相同,那么任何人都按照make列的升序字母顺序...

所以我想构建单个SQL查询,它给出了如下结果..

+--------+----------+---------+  
| amount | make     | product |  
+--------+----------+---------+  
|    100 | Nokia    | Mobiles |   
|    300 | Lava     | Mobiles |   
|    100 | Floyer   | Gift    |   
|    300 | Feeling  | Gift    |   
+--------+----------+---------+ 

请帮我构建这样的查询..

3 个答案:

答案 0 :(得分:1)

这应该对你有帮助..

第一个有错误,现在更新了。

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

与它和小提琴手玩得开心: http://sqlfiddle.com/#!2/bdd1a/115/0

答案 1 :(得分:0)

试试这个:

select * from table1 ORDER BY amount DESC LIMIT 2;

答案 2 :(得分:0)

SELECT amount, make,product
FROM 
  (SELECT  ROW_NUMBER() OVER (PARTITION BY product ORDER BY amount) AS RowID,*
   FROM Table1) RESULT
WHERE RowID <= 2

这在PostgreSQL中运行良好, mysql不支持窗口函数,通过在mysql refer

中获取类似的窗口函数