1

数据库是 AdventureWorks。

select COUNT(*) as 'Number of times a product is sold at same quantity' 
from
  Sales.SalesOrderDetail 
group by 
         OrderQty, ProductID 
order by 
         COUNT(*) desc

这将返回如下数据:

Number of times a product is sold at same quantity
--------------------------------------------------
4279
3216
3095
2376
2334
2319
2234
2201
2121
2025
1712
1488
1396
1161
1044

和其他 2600 多行。

我有兴趣获得 4279 作为输出。

我无法应用 Max,因为它不适用于聚合函数或子查询。反正我试过了。没用。

我猜我不能,因为 count(*) 不是一列。但如果有办法:

我怎样才能获得最大的这种输出?

4

1 回答 1

2

只需添加TOP以限制结果数量

select TOP 1 COUNT(*) as 'Number of times a product is sold at same quantity' 
from  Sales.SalesOrderDetail 
group by  OrderQty, ProductID 
order by  COUNT(*) desc

更新 1

WITH results 
AS
(
  select COUNT(*) as [Number of times a product is sold at same quantity],
         DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) rank_no 
  from   Sales.SalesOrderDetail 
  group   by OrderQty, ProductID 
)
SELECT [Number of times a product is sold at same quantity]
FROM   results
WHERE  rank_no = 2
于 2013-03-16T11:31:53.313 回答