SQL选择组查询

时间:2012-07-10 06:13:03

标签: mysql sql database

以下是我的表

表1

+--------+----------+---------+  
| amount | make     | product |  
+--------+----------+---------+  
|    100 | Nokia    | Mobiles |   
|    300 | Samesung | Mobiles |   
|    700 | Micromax | Mobiles |   
|   1000 | Karbonn  | Mobiles |   
|    500 | Lava     | Mobiles |   
|    100 | Floyer   | Gift    |   
|    500 | Arichies | Gift    |   
|    300 | Feeling  | Gift    |   
+--------+----------+---------+  

现在我想为每种产品显示两个最高金额...

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

+--------+----------+---------+  
| amount | make     | product |  
+--------+----------+---------+  
|   1000 | Karbonn  | Mobiles |   
|    700 | Micromax | Mobiles |   
|    500 | Arichies | Gift    |   
|    300 | Feeling  | Gift    |   
+--------+----------+---------+  

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

5 个答案:

答案 0 :(得分:10)

您可以使用此解决方案根据amount检索“ group-wise maximum ”:

SELECT a.*
FROM Table1 a
INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount
GROUP BY a.amount, a.product
HAVING COUNT(*) <= 2

只需将2更改为您要为每个产品检索的 top 行。

如果您想要检索每个产品的最低两行,只需将<=中的INNER JOIN符号更改为>=

您可以在这里找到解决方案:SQL-Fiddle Demo

答案 1 :(得分:4)

select product, make, amount, rnk
from (
  select l.product, l.make, l.amount, count(*) as rnk
  from table1 as l
  left join table1 as r
  on (r.product = l.product and l.amount <= r.amount) 
  group by l.product, l.make
) a
where rnk <= 2

请参阅此处的ideea和其他示例:http://www.xaprb.com/blog/2005/09/27/simulating-the-sql-row_number-function/

sql fiddle基于zane bien测试数据。

答案 2 :(得分:1)

SELECT a.*
FROM Table1 a
INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount
GROUP BY a.amount, a.product
HAVING COUNT(*) <= 2
ORDER BY a.amount desc

请参阅http://sqlfiddle.com/#!2/9ba82/1

答案 3 :(得分:0)

select top 2 amount, make, product from table1 
where product='Mobiles'
order by amount desc
union
select top 2 amount, make, product from table1 
where product='Gift'
order by amount desc

答案 4 :(得分:0)

您可以通过两种方式完成此操作: 1)添加将反映订单的行索引列,然后选择行&lt; = 2

的所有行
SELECT amount, make,product
FROM 
(SELECT  ROW_NUMBER() OVER (PARTITION BY [product] ORDER BY [amount] DESC) AS [RowID],*
FROM [dbo].[Table1]) RESULT
WHERE RowID <= 2

2)您也可以将表格加入其中

SELECT a1.* FROM Table1 AS a1
  LEFT JOIN Table1 AS a2 
    ON a1.product = a2.product AND a1.amount<= a2.amount
GROUP BY a1.product
HAVING COUNT(*) <= 2;