2013-02-12 130 views
1

我有一個包含用戶名和刪除狀態的表。重複的用戶名已刪除狀態組合是可能的。如果一個用戶名有多個條目的狀態爲1,那麼我需要將每個用戶名的一個條目的刪除狀態更新爲0。更新SQL Server中每個唯一記錄的一個條目

考慮以下數據:

Name EmpId Deleted 
-------------------- 
A  01  1 
A  01  1 
B  02  1 
B  02  0 
C  03  1 

要求:名稱A和C的一個條目應當被更新爲0(已刪除狀態)。

declare @testTable table (Name varchar(10), EmpId varchar(10), Deleted tinyint) 

insert into @testTable 
select 'A', '01', 1 UNION ALL 
select 'A', '01', 1 UNION ALL 
select 'B', '02', 1 UNION ALL 
select 'B', '02', 0 UNION ALL 
select 'C', '03', 1 

select * from @testTable 
+1

你有沒有嘗試任何事情你自己? – 2013-02-12 11:25:47

+0

我無法爲此寫入更新,因此我爲每個沒有0狀態的用戶名插入一個新條目。 – TechDo 2013-02-12 11:31:45

+1

您寫道:「多個條目已刪除狀態爲1」,然後您寫道:「要求:名稱A和C的一個條目應更新爲0(已刪除狀態)。」爲什麼C應該被刪除?我們在你的例子中只有一個名字「C」 – 2013-02-12 11:33:42

回答

1

試試這個;

;with cte as 
(
    select name, empId, deleted, 
     row_number() over (partition by name, empId order by deleted desc) rn 
    from T 
) 
Update cte set deleted = 0 
where rn <> 1 and deleted = 1 

SQL FIDDLE DEMO

+0

我認爲第五行,即C不會被更新。請確認。 – TechDo 2013-02-12 11:39:52

+0

在您給定的數據示例中,'C'不*重複,這就是原因。 – Kaf 2013-02-12 11:41:16

+0

是的,描述並不完美。我還需要更新C的記錄。良好的邏輯任何方式。 – TechDo 2013-02-12 11:46:24

1

這裏有一個方法:

with toupdate as (
     select t.*, 
      row_number() over (partition by name, deleted order by deleted) as seqnum 
     from t 
    ) 
update toupdate 
    set deleted = 0 
    where deleted = 1 and seqnum = 1 
1

SqlFillde demo

with t1 as 
(
select *, ROW_NUMBER() OVER 
      (PARTITION BY EMPID order by deleted) as rn 
     from testtable 
) 
update t1 set deleted=0 where rn=1 and deleted=1 
1
declare @testTable table 
(
    Name varchar(10), 
    EmpId varchar(10), 
    Deleted tinyint 
) 

insert into @testTable 
select 'A', '01', 1 UNION ALL 
select 'A', '01', 1 UNION ALL 
select 'A', '01', 1 UNION ALL 
select 'B', '02', 1 UNION ALL 
select 'B', '02', 0 UNION ALL 
select 'B', '02', 0 UNION ALL 
select 'C', '03', 1 

select * from @testTable 
update @testTable set deleted=1 
BEGIN 
with t1 as 
(
select *, ROW_NUMBER() OVER 
      (PARTITION BY EMPID order by deleted) as rn 
     from @testTable 
) 
update t1 set deleted=0 where rn=1 and deleted=1 
END 
select * from @testTable 
0
UPDATE A 
    SET Deleted = (CASE WHEN RowNum = 1 THEN 0 ELSE Deleted END) 
    FROM 
    (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Deleted) AS RowNum 
    FROM @testTable A WHERE Name NOT IN (SELECT Name FRom @testTable B Where Deleted=0) 
    ) A 
相關問題