I know we can generate row_number in select statement. But row_number starts from 1, I need to generate from 2 and onwards.
example
party_code
----------
R06048
R06600
R06791
(3 row(s) affected)
I want it like
party_code serial number
---------- -------------
R06048 2
R06600 3
R06791 4
Current I am using below select statement for generate regular row number.
SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
How can modify above select statement and start from 2?
To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.
ROW_NUMBER() function is used to generate a serial/row number for a given record set returned by the select query. We have to use ORDER BY clause along with ROW_NUMBER() function to generate row numbers so that the numbers are assigned to the specific order.
The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times. Let us see an example. Firstly, we will create a table using the CREATE command.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .
SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
to add: ROW_NUMBER()
has an unusual syntax, and can be confusing with the various OVER
and PARTITION BY
clauses, but when all is said and done it is still just a function with a numeric return value, and that return value can be manipulated in the same way as any other number.
I don't know much about SQL Server but either one of these will work:
SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
OR
SELECT party_code, serial_numer + 1 AS [serial number] FROM
(SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable)
ORDER BY party_code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With