Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Numbering rows in a select

Author  Topic 

olibara
Yak Posting Veteran

94 Posts

Posted - 2012-07-08 : 02:16:25
Hello

Is it possible in SQL to give an incremental number to the rows of a select

Thanks for your help

flamblaster
Constraint Violating Yak Guru

384 Posts

Posted - 2012-07-08 : 03:08:06
Yes, you can use the Row_Number() function. You need to determine how it will be ordered though in order to set up a sequence.

example:

declare @Customers table (CustomerId int, LastName varchar(20), FirstName varchar(20), Gender char(1))
insert into @Customers (CustomerId, LastName, FirstName, Gender)

values
(1, 'Jones', 'Martha', 'F'),
(2, 'Tyler', 'Rose', 'F'),
(3, 'Noble', 'Donna', 'F'),
(4, 'Jenkins', 'Sam', 'M'),
(5, 'Dennison', 'Kyle', 'M'),
(6, 'Atkins', 'Jim', 'M')

select CustomerId, Lastname, Firstname, Gender, ROW_NUMBER() OVER (Partition By Gender Order by Lastname, Firstname) as Sequence
from @Customers

(6 row(s) affected)
CustomerId LastName FirstName Gender Sequence
----------- -------------------- -------------------- ------ --------------------
1 Jones Martha F 1
3 Noble Donna F 2
2 Tyler Rose F 3
6 Atkins Jim M 1
5 Dennison Kyle M 2
4 Jenkins Sam M 3

(6 row(s) affected)


In the sample problem, you'll see that you the query is setting up a sequence based on the gender and sorted by lastname then firstname. As long as you know the criteria for which you want to create a sequence, you should be good to go.
Go to Top of Page

olibara
Yak Posting Veteran

94 Posts

Posted - 2012-07-08 : 04:54:21
Thank you very much

And I've seen that you can use Partition by NULL to get an incremental number on the whole select !
Go to Top of Page

flamblaster
Constraint Violating Yak Guru

384 Posts

Posted - 2012-07-08 : 10:25:37
Welcome
Go to Top of Page
   

- Advertisement -