3

I have a table with 2 PK Columns that I need to populate. The first column "ID" is already populated, I need to generate and populate the "SeqNum" column with int's like in my example below. There obviously cannot be the same SeqNum in the same record as the same ID because they are both PK's(I'm sure you know what I mean). How can I accomplish this?

It is a simple query like so:

Insert into @TempTable
Select A.ID
      ,1 --not sure what to do here
      ,B.Col3
      --and other columns
From Blah A Join Blah2 B on B.ID = A.ID

I've tried something like and it didn't work:

(Select max(ISNULL(SeqNum, 0)) + 1 From @TempTable Where ID = A.ID)

Any help is very much welcomed. Maybe I have to loop?

Example output I need:

PK  PK
ID  SeqNum
1111    1
1111    2
1111    3
2222    1
2222    2
2222    3
3333    1
4444    1
5555    1
5555    2
3
  • If we assume this is SQL server or postgresql then John's answer seems to fit nicely. Commented Dec 29, 2016 at 21:56
  • Agreed. If zanq was looking for a list of N items, it would be different. Commented Dec 29, 2016 at 22:01
  • Added sql-server tag based on the (non-standard) syntax used in the accepted answer Commented Dec 29, 2016 at 22:33

1 Answer 1

7

If I understand the question, Row_Number() would be a good fit here

Select ID
       ,SeqNum = Row_Number() over (Partition By ID Order By (Select NULL))
 From  ...
Sign up to request clarification or add additional context in comments.

2 Comments

YES! Thank you! It is exactly what I need!
@zanq Happy to help. It would be well worth your time to get comfortable with with Window Functions. They can be invaluable. cheers

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.