A few times I've needed to create a numbered list from a SQL script where the underlying table didn't have numeric data types.
Sometimes
something like this is from an internal customer, other times it is needed for
development purposes. It's a fairly easy script that could be easily
implemented so you don't have to make a temp table or variable table just to
have a numbered list.
The
keyword and syntax is as follows:
ROW_NUMBER() OVER (PARTITION BY <column_name> ORDER BY <column_name>)
That’s it! As a quick
example, here it is on the AdventureWorks2012 database. The query:
SELECT p.FirstName, p.LastName, e.JobTitle ,
ROW_NUMBER() OVER (PARTITION BY p.PersonType ORDER BY p.LastName) AS place
FROM person.person p
INNER JOIN HumanResources.Employee e ON e.BusinessEntityID = p.BusinessEntityID
Returns:
Now the PARTITION BY part is kind of like doing a “count()” function when writing
an aggregate query in that you are counting the same instances of that column
(every person in the above query is an employee and we are numbering each
instance of an employee, the numbering process would re-start if we included
non-employees).
A fairly simple coding addition that can be included in
every query.
Comments
Post a Comment