I have a project where I have a list of barcodes, and I need to associate them to record numbers in the correct sequence based on a second column.
My data looks like this:
Coupon Code | Code Type | Sequence 1234567890 | 1 | NULL 9876543210 | 1 | NULL 5464654222 | 2 | NULL 4554222558 | 3 | NULL 5464622154 | 3 | NULL 5688979465 | 3 | NULL
And then I have another set of data like this:
Sequence | Code Type 1 | 3 2 | 3 3 | 1 4 | 2 5 | 1 6 | 3
Is there any cheap way to join these two data sets such that I can assign the sequence in the first table based on the second? It is really arbitrary which barcode gets assigned first, as long as it is the correct barcode type. I have already done a cursor and it was way too slow.
Any suggestions? I can do my own research, just someone pointing me in the right direction would be a big help. Sorry for poor formatting.
Advertisement
Answer
If I understand correctly you can use row_number()
:
select t1.*, t2.sequence from (select t1.*, row_number() over (partition by code_type order by couponcode) as seqnum from table1 t1 ) t1 join (select t2.*, row_number() over (partition by code_type order by sequence) as seqnum from table2 t2 ) t2 on t1.code_type = t2.code_type and t1.seqnum = t2.seqnum;
This type of logic can be incorporated into an update
if you need to assign the value. However, the syntax for that depends on the database you are using.
EDIT:
The update in SQL Server would be:
update t1 set t1.sequence = t2.sequence from (select t1.*, row_number() over (partition by code_type order by couponcode) as seqnum from table1 t1 ) t1 join (select t2.*, row_number() over (partition by code_type order by sequence) as seqnum from table2 t2 ) t2 on t1.code_type = t2.code_type and t1.seqnum = t2.seqnum;