I have this set of data in the 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
I want to update this table and filled up doc_lineno & stk_lineno column with number to be like below :
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
how to make it using this code for both column.
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;
note: for doc_lineno, number remain same for same stk_code in the same doc_no and will reset on stk_code and doc_no. for stk_lineno, number will reset when diff. stk_code
Assuming that the table has an identity col to identify each row.
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
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.