我有以下表格结构。
我只想将 SubId 更新为空的所有行,其中 RawLineNumber 增加1, SeqNumber 以1递增。
RawlineNumber Claimid SubId SeqNumber
1 6000 A100 1
2 6000 NULL 2
3 6000 NULL 3
10 6000 A200 1
11 6000 NULL 2
25 6000 A300 1
26 6000 NULL 2
27 6000 NULL 3
我想更新
原始 RawLineNumber 2和3与A100,
使用A200, RawLineNumber 11 SubId
RawLineNumber SubId 26和27与A300。
我有一个光标可以完成工作,但是我可以用CTE来处理它吗?
答案 0 :(得分:7)
UPDATE m
SET subid = q.subid
FROM mytable m
CROSS APPLY
(
SELECT TOP 1 subid
FROM mytable mi
WHERE mi.rawLineNumber < m.rawLineNumber
AND mi.subid IS NOT NULL
ORDER BY
rawLineNumber DESC
) q
WHERE m.subid IS NULL
答案 1 :(得分:2)
由于要求使用重复的解决方案,我决定写一个。它也适用于Seqnumbers和RawlineNumber
中的间隙declare @t table (RawlineNumber int, Claimid int, SubId varchar(5), SeqNumber int)
insert @t values(1, 6000, 'A100', 1)
insert @t values(2, 6000, NULL, 2)
insert @t values(3, 6000, NULL, 3)
insert @t values(10, 6000, 'A200', 1)
insert @t values(11, 6000, NULL, 2)
insert @t values(25, 6000, 'A300', 1)
insert @t values(26, 6000, NULL, 2)
insert @t values(27, 6000, NULL, 3)
;with cte as
(
select Rawlinenumber, SeqNumber, SubId
from @t where SubId is not null and SeqNumber = 1
union all
select t.Rawlinenumber, t.SeqNumber, c.SubId
from cte c
join
@t t
on c.Rawlinenumber + 1 = t.Rawlinenumber
and c.SeqNumber + 1 = t.SeqNumber
where t.SubId is null and t.SeqNumber > 1
)
update t
set SubId = c.SubId
from @t t join cte c
on c.Rawlinenumber = t.Rawlinenumber
where t.SeqNumber > 1
select * from @t
答案 2 :(得分:0)
一个不那么简单的SQL脚本应该实现你想要的目标:
update my_table t1 set t1.subid =
(select t2.subid from my_table t2
where t2.rawlinenumber < t1.rawlinenumber
and t2.seqnumber = 1
and t2.rawlinenumber = (
select max(t3.rawlinenumber)
from my_table t3
where t3.seq_number = 1
and t3.rawlinenumber <= t2.rawlinenumber)
where t1.subid is null;
内部子选择(T3)给出了当前行之前seqnumber = 1的最后一行, 外部子选择为我们提供了该行的SubID(使用窗口函数会更有效,但由于你没有提到特定的RDBMS,我坚持这个:-))