2012-07-10 64 views
10

下面是我的表SQL选择组查询

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

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

回答

10

您可以使用此解决方案来检索基础上,amount的“组间最大”:

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很多你想每次检索顶部行产品。

如果你想获取每个产品的最低两行,你可以简单地在INNER JOIN<=标志更改为>=

可以摆弄这个解决方案在这里:SQL-Fiddle Demo

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

答案不一般。如果你有100个产品呢? – 2012-07-10 06:29:06

0

您可以通过两种方式做到这一点: 1)添加行索引列,将反映订单,然后选择与行< = 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; 
+0

mysql没有分析功能。 – 2012-07-10 06:29:32

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