删除重复记录并保留一个

时间:2015-07-09 06:28:54

标签: sql sql-server-2008 tsql duplicates duplicate-removal

使用T-SQL。

我的问题是我有一个usersidlocationid的列表。 用户只能拥有一个位置。

通过以下查询,我得到一个包含多个位置ID的所有用户的列表:

SELECT * 
FROM Userslocation
WHERE [USER] IN (
    SELECT [USER]  
    FROM Userslocation
    GROUP BY [User] 
    HAVING COUNT(*) > 1
    )

结果我得到了

location User
80653    83269
63150    83269
80653    84035
63150    84035
80653    85097
63150    85097

我想保留一个结果并删除其余的

location User
80653    83269
80653    84035
80653    85097

3 个答案:

答案 0 :(得分:0)

使用用户的最大位置返回每位用户一次:

select user, max(location)
from tablename
group by user
having count(*) > 1

答案 1 :(得分:0)

你需要像 CTE

这样的东西
WITH UserslocationCTE AS (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY [User] 
    ORDER BY location)'RowRank'
    FROM Userslocation)
DELETE FROM UserslocationCTE 
WHERE RowRank > 1

答案 2 :(得分:0)

为usersLocation插入增量ID。然后删除大于第一个ID的记录。例如。

Query
___
SELECT * 
FROM Userslocation
WHERE [USER] IN (
    SELECT [USER]  
    FROM Userslocation
    GROUP BY [User] 
    HAVING COUNT(*) > 1
    )

将显示以下结果

ID   location User
1    80653    83269
2    63150    83269
3    80653    84035
4    63150    84035
5    80653    85097
6    63150    85097

现在你可以做到

 SELECT *
--or delete 
FROM Userlocation
WHERE id NOT IN (
        SELECT MIN(id)
        FROM Userlocation
        GROUP BY [USER]
        HAVING COUNT(*) > 1

        UNION

        SELECT MIN(id)
        FROM Userlocation
        GROUP BY [USER]
        HAVING COUNT(*) = 1
        )