0

on SQL Server.

I am importing a table that looks like this:

ForeignID || Detail 
ID1       || detail1
ID1       || detail2
ID1       || detail3
ID2       || detail1
ID3       || detail1
ID3       || detail2

Into a new table that looks like this:

ForeignID  || ItemNo   || Detail
ID1        || 1        || detail1
ID1        || 2        || detail2
ID1        || 3        || detail3
ID2        || 1        || detail1
ID3        || 1        || detail1
ID3        || 2        || detail2

How do I automatically generate the "ItemNo" column values? They should be an auto-incrementing integer that get resets whenever ForeignID changes. ForeignID and ItemNo will act as Composite Primary Key for the new table.

It'll be great to be able to do this during the INSERT INTO - SELECT process. Otherwise, a separate query would work as well.

2 Answers 2

2

This is an easy task for ROW_NUMBER:

insert into target
select
   ForeignID
  ,row_number()
   over (partition by ForeignID order by Detail) 
  ,Detail 
from source
0

You can do it using row number, something like this:

insert into ... 
select 
    ForeignID, 
    Detail, 
    row_number() over (partition by ForeignID order by Detail) as RowNum
order by
  ForeignID,
  Detail

The rownum will start numbering every time ForeignID changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.