如何在表sql server中找到第一个重复行

时间:2013-12-31 07:30:25

标签: sql sql-server

我正在研究SQL Server。我有一张表,其中包含大约75000条记录。其中有几个重复的记录。所以我写了一个查询来知道哪条记录重复了多少次,

SELECT [RETAILERNAME],COUNT([RETAILERNAME]) as Repeated FROM [Stores] GROUP BY [RETAILERNAME]

它给我的结果如,

---------------------------
RETAILERNAME  |  Repeated
---------------------------
    X         |    4
---------------------------
    Y         |    6
---------------------------
    Z         |    10
---------------------------

在X记录的4个记录中,我只需要取X的第一个记录。

所以我想从第一行重复记录中检索所有字段。即,取所有RETAILERNAME ='X'的记录,我们会得到一些不。对于重复记录,我们只需从它们获取第一行。 请指导我。

3 个答案:

答案 0 :(得分:3)

您可以尝试使用ROW_NUMBER

这样的东西
;WITH Vals AS (
        SELECT  [RETAILERNAME],
                ROW_NUMBER() OVER(PARTITION BY [RETAILERNAME] ORDER BY [RETAILERNAME]) RowID
        FROM    [Stores ]
)
SELECT  *
FROm    Vals
WHERE   RowID = 1

SQL Fiddle DEMO

如果需要,你也可以删除重复项(但是要小心这是永久性的

;WITH Vals AS (
        SELECT  [RETAILERNAME],
                ROW_NUMBER() OVER(PARTITION BY [RETAILERNAME] ORDER BY [RETAILERNAME]) RowID
        FROM    Stores 
)
DELETE
FROM  Vals
WHERE RowID > 1;

答案 1 :(得分:0)

WITH cte 
     AS (SELECT [retailername], 
                Row_number() 
                  OVER( 
                    partition BY [retailername] 
                    ORDER BY [retailername])'RowRank' 
         FROM   [retailername]) 
SELECT * 
FROM   cte 

答案 2 :(得分:0)

您可以在

下编写查询

SELECT TOP 1 * FROM [Stores] GROUP BY [RETAILERNAME] 有你的病情