Question

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

Was it helpful?

Solution

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
;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top