2012-07-10 92 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