我在wrntybank_table中有这组数据:
doc_no doc_lineno stk_code stk_lineno serial_no warranty_no
doc1 NULL ABC NULL ABC1 WRN1
doc1 NULL ABC NULL ABC5 WRN5
doc1 NULL DEF NULL ABC2 WRN2
doc2 NULL ABC NULL ABC3 WRN3
doc4 NULL HJI NULL ABC4 WRN4
doc4 NULL HJI NULL ABC6 WRN6
我想更新此表并填写doc_lineno& stk_lineno列的编号如下所示:
doc_no doc_lineno stk_code stk_lineno serial_no warranty_no
doc1 1 ABC 1 ABC1 WRN1
doc1 1 ABC 2 ABC5 WRN5
doc1 2 DEF 1 ABC2 WRN2
doc2 1 ABC 1 ABC3 WRN3
doc4 1 HJI 1 ABC4 WRN4
doc4 1 HJI 2 ABC6 WRN6
如何使用此代码为两个列创建它。
with toupdate as (
select Document,
10 * row_number() over (partition by Document order by (select NULL)) as val
from t
)
update toupdate
set line_num = val;
注意:对于doc_lineno,同一doc_no中相同stk_code的数字保持相同,并将在stk_code和doc_no上重置。 对于stk_lineno,数字将在diff时重置。 stk_code
答案 0 :(得分:2)
假设该表具有标识col以标识每一行。
with cte (id, dln, sln)
as
(
select id, dense_rank() over (partition by doc_no order by stk_code asc) as dln
, row_number() over (partition by doc_no, stk_code order by serial_no asc) as sln
from @t_test
)
update @t_test
set doc_lineno = cte.dln
, stk_lineno = cte.sln
from @t_test as t
inner join cte as cte
on t.id = cte.id
;