6

我的问题类似于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    |   
+--------+----------+---------+ 

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

4

3 回答 3

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

于 2012-09-26T06:54:26.810 回答
0

试试这个:

select * from table1 ORDER BY amount DESC LIMIT 2;
于 2012-09-26T06:48:41.377 回答
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 中获得类似的窗口函数参考

于 2012-09-26T06:54:13.173 回答