Row_Number() over()
over()里面有两个参数
Partition by
将 FROM 子句生成的结果集划入应用了 ROW_NUMBER 函数的分区。 value_expression 指定对结果集进行分区所依据的列。 如果未指定 PARTITION BY,则此函数将查询结果集的所有行视为单个组。
Order by
ORDER BY 子句可确定在特定分区中为行分配唯一 ROW_NUMBER 的顺序。 它是必需的。
Select a.ProductID,a.SupplierID,a.CategoryID, ROW_NUMBER() over(partition by CategoryID ,SupplierID order by ProductID)as RowN from (
SELECT TOP 10 [ProductID]
,[ProductName]
,[SupplierID]
,[CategoryID]
,[QuantityPerUnit]
,[UnitPrice]
,[UnitsInStock]
,[UnitsOnOrder]
,[ReorderLevel]
,[Discontinued]
FROM [Northwind].[dbo].[Products]) a
获得结果:
Note:此处的数据稍微有点问题,最后会说到。
此次并没有达到去除重复的结果,但稍微看下就发现了多了一行RowN。
这个是根据SupplierID,CategoryID分区并根据ProductID升序获得的行号。所以去除重复也就非常容易了。
Select* from (
Select a.ProductID,a.SupplierID,a.CategoryID, ROW_NUMBER() over(partition by CategoryID ,SupplierID order by ProductID)as RowN from (
SELECT TOP 10 [ProductID]
,[ProductName]
,[SupplierID]
,[CategoryID]
,[QuantityPerUnit]
,[UnitPrice]
,[UnitsInStock]
,[UnitsOnOrder]
,[ReorderLevel]
,[Discontinued]
FROM [Northwind].[dbo].[Products]) a) b where b.RowN=1
获得结果:
顺带附上b.RowN=2结果: