|
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
*/
|