Creating sequences for subsets of a table

I have a table in SqlServer 9 with form data

Code    Number
J       0
J       5
J       8
Y       2
Y       8

I would like to add a column with a number with an internal sequence of numbers for each code so that my table looks like this:

Code    Number   Seq
J       0        1
J       5        2
J       8        3
Y       2        1
Y       8        2

Does anyone have any suggestions on the best way to accomplish this?

0
source share
2 answers

Take a look at the function ROW_NUMBER () .

DECLARE @Number TABLE (
    Code        nvarchar(1)
,   Number      int
)


INSERT @Number VALUES ('J', 0)
INSERT @Number VALUES ('J', 5)
INSERT @Number VALUES ('J', 8)
INSERT @Number VALUES ('Y', 2)
INSERT @Number VALUES ('Y', 8)


SELECT * FROM @Number


SELECT  Code
,       Number
,       ROW_NUMBER() OVER(PARTITION BY Code ORDER BY Code) AS Seq
FROM    @Number
+5
source

find the row_number () and RANK () functions in the On Line book

+1
source

Source: https://habr.com/ru/post/1709536/


All Articles