更新SQL Server中每个唯一记录的一个条目

时间:2013-02-12 11:22:31

标签: sql sql-server sql-server-2005 sql-update

我有一个包含用户名和已删除状态的表。可以使用重复的用户名删除状态组合。如果用户名有多个条目,删除状态为1,那么我需要将已删除状态更新为0,每个用户名的一个条目。

考虑以下数据:

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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