Wednesday, July 8, 2009

Simple sample of Row_Num command

Again, using the SQL Server Northwinds Database . . . Say, I want to find the most expensive product for each Category in the Product Table:

Select
CategoryID,
ProductID,
ProductName,
UnitPrice,
UnitsAvailable

from
(Select CategoryID,
ProductID,
ProductName,
UnitPrice,
UnitsAvailable = UnitsInStock+UnitsOnOrder,
[RowNumber] = row_number() over(partition by CategoryID order by UnitPrice desc)
from dbo.Products) as vt

where [RowNumber] = 1


P.S. I hate that I appear to lose formatting when the blog is posted. . . i should invest some time in learning to tweak html!

No comments:

Post a Comment