1

ユーザー名と削除済みステータスを含むテーブルがあります。重複したユーザー名の削除ステータスの組み合わせが可能になる場合があります。ユーザー名に削除済みステータスが 1 のエントリが複数ある場合は、各ユーザー名の 1 つのエントリの削除済みステータスを 0 に更新する必要があります。

次のデータを検討してください。

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

要件: 名前 A と C の 1 つのエントリを 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
4

5 に答える 5

1

SqlFilldeデモ

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
于 2013-02-12T11:46:16.683 に答える
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

于 2013-02-12T11:34:46.680 に答える
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
于 2013-02-12T11:48:56.417 に答える
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
于 2013-02-12T11:35:23.317 に答える
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
于 2014-01-14T12:52:42.407 に答える