2013-02-12 120 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 
相关问题