我有下表,并且我想将只有一个具有重复名称的记录的deleted列的值设置为零。
id name deleted
------------------------
1 a 1
2 a 1
3 a 1
4 b 1
5 c 1
6 d 1
所以输出将是:
id name deleted
------------------------
1 a 0
2 a 1
3 a 1
4 b 0
5 c 0
6 d 0
答案 0 :(得分:3)
如果你的dbms是SQL-Server(> = 2005),你可以CTE
使用ROW_NUMBER
:
WITH CTE AS
(
SELECT ID, Name, Deleted,
RN = ROW_NUMBER() OVER(PARTITION BY name ORDER BY ID)
FROM dbo.T
)
UPDATE CTE
SET Deleted = 0
WHERE RN = 1
答案 1 :(得分:1)
UPDATE Tbl SET deleted = 0 WHERE id IN
(SELECT MIN(id) FROM Tbl GROUP BY name)
答案 2 :(得分:0)
UPDATE A
SET A.deleted = 0
FROM Tbl A
LEFT JOIN Tbl B
ON A.Name = B.Name
AND A.Id > B.Id
WHERE B.Id IS NULL