原文地址:http://www.cnblogs.com/fatbird/p/Sql-Remove-duplicate.html
Row_Number() over()
over()里面有两个参数
Partition by value_expression
将 FROM 子句生成的结果集划入应用了 ROW_NUMBER 函数的分区。 value_expression 指定对结果集进行分区所依据的列。 如果未指定 PARTITION BY,则此函数将查询结果集的所有行视为单个组。
也就是说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结果: