如何在一个ID下合并具有相同名称的用户

时间:2017-08-25 18:03:09

标签: sql sql-server sql-update

我正在使用一组数据,其中有一个ID字段和一个USERS字段。某些用户具有相同的名称但具有不同的ID。我需要帮助整合数据集,以便每个用户都有一个唯一的ID。在下面的示例中,您将看到我如何在单个ID(1)下合并两个Bob用户。任何帮助将非常感激。谢谢!

**ID         User**
1          Bob 
2          Tom
3          Jim
4          Dan
5          Bob

**ID         User**
1          Bob 
2          Tom
3          Jim
4          Dan

3 个答案:

答案 0 :(得分:1)

您可以使用窗口ROW_NUMBER函数来识别第一条记录,并删除其他所有内容:

;With ToDelete As
(
    Select  *,
            Row_Number() Over (Partition By [User] Order By Id Asc) As RN
    From    Users
)
Delete  ToDelete
Where   RN <> 1

答案 1 :(得分:1)

创建一个CTE,然后从CTE中删除。应该很快。

/* SETUP */
CREATE TABLE #test (id int identity, user varchar(10))
INSERT INTO #test (user)
VALUES ('bob') , ('Tom') , ('Jim') , ('Dan') , ('Bob')
; 

/* BEFORE */
SELECT * FROM #test ;

/* DELETE QUERY */
WITH fullList AS (
    SELECT id, user
        , ROW_NUMBER() OVER ( PARTITION BY user ORDER BY id ) AS rn
    FROM #test
)
DELETE FROM fullList WHERE rn > 1
;

/* AFTER */    
SELECT * FROM #test ;

答案 2 :(得分:0)

第一步,查找重复记录(相同的ID和用户)

WITH CTE
AS (SELECT *,
        ROW_NUMBER() OVER (PARTITION BY id,User ORDER BY ID) AS RowNumber
    FROM #Employees
   )
SELECT * FROM CTE

--DELETE FROM CTE WHERE RowNumber > 1;

然后更改Query以查找相同的用户:

WITH CTE
AS (SELECT *,
        ROW_NUMBER() OVER (PARTITION BY User ORDER BY ID) AS RowNumber
    FROM #Employees
   )
SELECT * FROM CTE
--DELETE FROM CTE WHERE RowNumber > 1;