DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
 
 
SITE SEARCH SQLUSA.com VIDEOS
 
 
SQL E/BOOKS   WORLD, USA & SQL NEWS   FORMAT
SCRIPTS SQL 2005 SQL 2008 ARTICLES
How to sequentially number the result set?

 

The following Microsoft SQL Server T-SQL code examples demonstrate how to create a sequence number for an ordered set without ties:

-- T-SQL SELF-JOIN usage for autonumbering

USE Northwind;

SELECT   SeqNo = count(* ),

         Name = a.LastName + ', ' + a.FirstName

FROM     Northwind.dbo.Employees a

         INNER JOIN Northwind.dbo.Employees b

           ON a.LastName + ', ' + a.FirstName >= b.LastName + ', ' + b.FirstName

GROUP BY a.LastName + ', ' + a.FirstName

ORDER BY a.LastName + ', ' + a.FirstName

/*

SeqNo Name

1     Buchanan, Steven

2     Callahan, Laura

3     Davolio, Nancy

4     Dodsworth, Anne

5     Fuller, Andrew

....

*/

 

-- SQL Server 2005 and on - ROW_NUMBER ranking function

SELECT      SeqNo = ROW_NUMBER() OVER (ORDER BY LastName,FirstName),

            Name = p.LastName + ', ' + p.FirstName,

            BusinessEntityID

FROM AdventureWorks2008.Person.Person p

/*

SeqNo Name              BusinessEntityID

1     Abbas, Syed       285

2     Abel, Catherine   293

3     Abercrombie, Kim  295

4     Abercrombie, Kim  2170

5     Abercrombie, Kim  38

*/

 

Exam Prep 70-461
SQL 2016 DESIGN & PROGRAMMING
 
 
 
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE