如何在SQL Server中获取包含第一行编号的重复行?

时间:2016-09-13 05:53:57

标签: sql sql-server sql-server-2012

我在下面写了一些查询,以便在SQL Server中使用Row_Number()来检索重复的客户。

 Cust_PKID ---------------+ CustomerID ----------------- + MobileNo
 1                        | A00001                       | 9000477444   
 2                        | A00002                       | 9000477444
 3                        | A00003                       | 9000477444

查询: -

Select TMP.CustID
From
(
   Select CustomerID CustID,
       Row_Number() Over(Partition By MobileNo Order By (Select Null)) As RowNo
   From dbo.Customers
) TMP
Where TMP.RowNo > 1

输出: -

Cust_PKID ---------------+ CustomerID ----------------- + MobileNo    
2                        | A00002                       | 9000477444
3                        | A00003                       | 9000477444

如何在单个select语句中检索包含第一个RowNo记录的记录?

1 个答案:

答案 0 :(得分:3)

您正在寻找COUNT() OVER()窗口函数而不是ROW_NUMBER

Select TMP.CustID
From
(
   Select CustomerID CustID,
       COUNT(1) Over(Partition By MobileNo) As RowNo
   From dbo.Customers
) TMP
Where TMP.RowNo > 1

这将带来所有重复的MobileNo条记录