Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate Serial numbers +Add 1 in select statement

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?

like image 401
James123 Avatar asked Sep 29 '11 15:09

James123


People also ask

How do I add a sequence number to a select query?

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.

How do I add series numbers in SQL?

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.

How do I select 1 in SQL?

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.

How do I generate an automatic number in SQL?

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) .


2 Answers

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.

like image 139
AakashM Avatar answered Oct 26 '22 23:10

AakashM


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
like image 44
Yahia Avatar answered Oct 27 '22 00:10

Yahia