删除重复值T-SQL的1个实例

时间:2013-07-04 11:08:02

标签: sql tsql sql-server-2008-r2

我目前有一个名为People的表。在此表中,有数千行数据遵循以下布局:

gkey |    Name |  Date       | Person_Id
1    |    Fred |  12/05/2012 | ABC123456
2    |    John |  12/05/2012 | DEF123456
3    |    Dave |  12/05/2012 | GHI123456
4    |    Fred |  12/05/2012 | JKL123456
5    |    Leno |  12/05/2012 | ABC123456

如果我执行以下操作:

SELECT [PERSON_ID], COUNT(*) TotalCount
FROM [Database].[dbo].[People]
GROUP BY [PERSON_ID]
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

我得到了回复:

Person_Id     | TotalCount
ABC123456     | 2

现在我想删除一行重复值,所以当我执行上面的查询时,我没有返回任何结果。这可能吗?

4 个答案:

答案 0 :(得分:7)

WITH a as
(
SELECT row_number() over (partition by [PERSON_ID] order by name) rn
FROM [Database].[dbo].[People]
)
DELETE FROM a
WHERE rn = 2

答案 1 :(得分:0)

试试这个

DELETE FROM [People]
WHERE gkey IN
(
   SELECT MIN(gkey)
   FROM [People]
    GROUP BY [PERSON_ID]
   HAVING COUNT(*) > 1
)

您可以使用MINMax

答案 2 :(得分:0)

DELETE FROM PEOPLE WHERE gkey=
(SELECT MAX(TABLE1.gkey) FROM (SELECT P.gkey, A.PERSON_ID,A.TotalCount FROM People P,(SELECT [PERSON_ID], COUNT(*) TotalCount
FROM [Database].[dbo].[People]
GROUP BY [PERSON_ID]
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC) A WHERE P.gkey=A.gkey) TABLE1 ) TABLE2

答案 3 :(得分:0)

使用Top关键字删除;

DELETE TOP(1) FROM [People]
WHERE Person_Id IN
(
   SELECT MIN([PERSON_ID])
   FROM [People]
   GROUP BY [PERSON_ID]
   HAVING COUNT(*) > 1

查询与Vassy发布的相同,只有Top(1)addded ...