0

Is there any way to generate a custom sequential number like the following? I want the Number to be incremented with grouping by the Code and Year.

Code    Year    Number
A       2016    1
A       2016    2
A       2016    3
B       2016    1
B       2016    2
C       2016    1
A       2017    1
A       2017    2

Any suggestion would be appreciated.

EDIT
Sorry, I was too ambiguous what I want. I want to generate the unique number when I query, so if I ask a new number in the above data context with Code:A and Year:2017, I want the Number to be 3. I guess to get the Number properly in a future I need to save the Code and Year with the Number.

2
  • 1
    Do you want to have this number in the table, or when you query the data? Commented May 27, 2016 at 5:21
  • Oh I forgot to mention that the generated number must be unique, so I guess the numbers have to be saved in the table Commented May 27, 2016 at 5:27

1 Answer 1

2

Use ROW_NUMBER to assign Number per Code,Year grouping.

SELECT *,
    Number = ROW_NUMBER() OVER(PARTITION BY Code, [Year] ORDER BY (SELECT NULL))
FROM tbl

Replace SELECT NULL with the column you want the order to be based from.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh such a quick reply. Thanks a lot! I guess all I need to do is save that number for a future inquiry.

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.