10

下面是我的表

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

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

4

5 回答 5

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

于 2012-07-10T06:26:55.530 回答
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/

和基于 zane bien 测试数据的sql fiddle 。

于 2012-07-10T06:26:15.580 回答
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

于 2012-07-10T06:33:58.707 回答
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
于 2012-07-10T06:24:29.090 回答
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;
于 2012-07-10T06:27:37.793 回答