我有一张包含员工ID和UserNames的表。某些员工ID是重复的,但UserName是不同的。我需要中断重复项并使用新的员工ID将它们添加回列表。
例如:
EMPID|UserName
1 | Josh
2 | John
2 | Kate
2 | Jorge
3 | Taylor
3 | Morgan
4 | Nathan
我需要将其切换为:
1|Josh
2|John
3|Taylor
4|Nathan
5|Kate
6|Jorge
7|Morgan
我知道要查找重复项的SQL。但要做这种举动,我很遗憾。
谢谢!
答案 0 :(得分:0)
DECLARE @TABLE TABLE (EMPID INT, UserName VARCHAR(10))
INSERT INTO @TABLE VALUES
(1 ,'Josh') ,(2 ,'John') ,(2 ,'Kate'),
(2 ,'Jorge'),(3 ,'Taylor'),(3 ,'Morgan'),4 ,'Nathan')
;WITH CTE AS
(
SELECT * , ROW_NUMBER() OVER (ORDER BY EMPID,UserName) + (SELECT MAX(EMPID) FROM @TABLE) New_ID
FROM @TABLE t
WHERE NOT EXISTS (SELECT EMPID , MAX(UserName) AS UserName1
FROM @TABLE
WHERE EMPID = t.EMPID
GROUP BY EMPID
HAVING MAX(UserName) = t.UserName)
)
UPDATE CTE
SET EMPID = New_ID
SELECT * FROM @Table
╔═══════╦══════════╗
║ EMPID ║ UserName ║
╠═══════╬══════════╣
║ 1 ║ Josh ║
║ 2 ║ Kate ║
║ 3 ║ Taylor ║
║ 4 ║ Nathan ║
║ 5 ║ John ║
║ 6 ║ Jorge ║
║ 7 ║ Morgan ║
╚═══════╩══════════╝