更新SQL Server中每个唯一记录的一个条目
问题描述:
我有一个包含用户名和删除状态的表。重复的用户名已删除状态组合是可能的。如果一个用户名有多个条目的状态为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
答
试试这个;
;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
答
这里有一个方法:
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
答
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
答
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
答
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
你有没有尝试任何事情你自己? – 2013-02-12 11:25:47
我无法为此写入更新,因此我为每个没有0状态的用户名插入一个新条目。 – TechDo 2013-02-12 11:31:45
您写道:“多个条目已删除状态为1”,然后您写道:“要求:名称A和C的一个条目应更新为0(已删除状态)。”为什么C应该被删除?我们在你的例子中只有一个名字“C” – 2013-02-12 11:33:42