2013-01-16 56 views
0

我有下表,並且我想將只有一個具有重複名稱的記錄的已刪除列的值設置爲零。僅爲其中一個重複記錄將列的值設置爲0?

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

[你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+1

你使用的是什麼rdbms? –

+0

帶有內部選擇的更新表,但沒有運氣 – Xerxes

回答

3

如果您的DBMS是SQL-服務器(> = 2005),你可以使用一個CTEROW_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 

DEMO

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 
1
UPDATE Tbl SET deleted = 0 WHERE id IN 
(SELECT MIN(id) FROM Tbl GROUP BY name) 
相關問題