简体   繁体   English

SQL生成序列号

[英]SQL Generate Sequence Numbers

I have a table with 2 PK Columns that I need to populate. 我有一个需要填充2个PK列的表。 The first column "ID" is already populated, I need to generate and populate the "SeqNum" column with int's like in my example below. 第一列“ ID”已经填充,我需要使用以下示例中的int生成并填充“ SeqNum”列。 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). 显然,同一记录中不能有与相同ID相同的SeqNum,因为它们都是PK(我确定您知道我的意思)。 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

If I understand the question, Row_Number() would be a good fit here 如果我理解这个问题,那么Row_Number()将非常适合

Select ID
       ,SeqNum = Row_Number() over (Partition By ID Order By (Select NULL))
 From  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM