posted 10/22/2010 by timmurphy - Views: [2074]
I recently had an opportunity to use the ROW_NUMBER() ranking function along with the OVER PARTITION BY clause. Here’s a simplified example of how I used it.
In this example the desired result is to get the first value in ColumnB for each group of Values in ColumnA.
ExampleTable:
ColumnA
ColumnB
1
a
b
c
2
d
e
f
2a
g
h
i
3
j
k
l
3.5
m
n
Here’s the query:
SELECT GroupNumber
,RankLetter
FROM (SELECT ColumnA AS GroupNumber
,ColumnB AS RankLetter
,ROW_NUMBER() OVER(PARTITION BY ColumnA ORDER BY (SELECT 1)) AS Ranking
FROM ExampleTable) AS TableAlias
WHERE Ranking = 1
Result:
GroupNumber
RankLetter
There may have been another way to accomplish this, but I liked learning the ranking function. Hopefully this can help if you need to do something similar.
Well stated Tim! Short and to the point.
Hi. Nice explanation in what you want and how to achive that.
Btw, you have already this information in my blog, with video examples also. Take a look:
http://www.bidn.com/blogs/marcoadf/bidn-blog/379/ranking-functions-row_number-vs-rank-vs-dense_rank-vs-ntile