我正在尝试查找SQL Server中特定列中的n个最大数字。
我们可以很容易地找到列中的最大值和第二大值。
但是我如何在一列中找到比如说5个最大的值呢?
发布于 2012-10-03 17:43:49
在MySql中,您可以使用[LIMIT {[offset,] row_count }]
这样做:
...
ORDER BY SomeField DESC
LIMIT @n;
对于SQL Server,您可以使用TOP(n)
获取前n项:
SELECT TOP(@n) SomeFieldName
FROM TABLE
ORDER BY SomeField DESC
例如:
SELECT TOP 5 items_sold
FROM tbl_PRODUCT
ORDER BY items_sold dESC
更新:如果您有另一个表families
,其中包含products表的外键family_ID
,并且您想要查找具有前n个系列id的所有产品,那么您可以这样做:
SELECT *
FROM Products WHERE family_ID IN
(
SELECT TOP 5 family_ID
FROM families
ORDER BY family_ID DESC
)
更新2:每个系列中最顶尖的产品:
;WITH cte
AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY family_ID ORDER BY items_sold DESC) row_num
FROM @Products
)
SELECT * FROM cte
where row_num = 1
Order by family_ID
发布于 2012-10-03 17:44:38
您为MySQL和SQL Server都添加了标记。在SQL Server中,您可以使用TOP
SELECT TOP 5 yourColumn
FROM yourTable
ORDER BY someColumn DESC;
TOP
限制返回的行数。要获得具有最大/最小值的数据,您需要包含一个ORDER BY
。
在MySQL中,您将使用LIMIT
在SQL Server中执行此操作的另一种方法是使用row_number()
select id
from
(
select id, row_number() over(order by id desc) rn
from yourtable
) x
where rn <= 5
请参阅SQL Fiddle With Demo
发布于 2012-10-03 17:50:14
sql服务器
select min(val)
from your_table
where val in (select top 5 val from your_table order by val desc)
mysql
select min(val)
from your_table
where val in (select val from your_table order by val desc limit 5)
https://stackoverflow.com/questions/12705789
复制相似问题