Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
VBChick
Starting Member
1 Post |
Posted - 2008-11-03 : 19:39:32
|
I wrote a ranking query utilizing the advice from Michael Valentine Jones in the following post:http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=48441. I would post my query, but it's simply a rewrite of Michael's suggestion utilizing the tables in my database. The query works wonderfully well when the query is in descending order, and I use it to get the top performers. And, I thought it would work equally as well when sorted in ascending order to get the bottom performers. But, the ranking doesn't work the same when the table is sorted ascending.So, for descending order I get data that looks like thisRegion Qty RankNorth 5 1North 4 2North 3 3South 11 1South 10 2But, when I sort the query in ascending order I get data that looks like this:Region Qty RankNorth 3 2North 4 3North 5 4South 10 18South 11 19Any ideas? Thanks in advance. |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-11-04 : 01:24:25
|
[code]DECLARE @Sample TABLE ( Region CHAR(5) NOT NULL, Qty TINYINT NOT NULL )INSERT @SampleSELECT 'North', 5 UNION ALLSELECT 'North', 4 UNION ALLSELECT 'North', 3 UNION ALLSELECT 'South', 11 UNION ALLSELECT 'South', 10-- AscendingSELECT s1.Region, s1.Qty, (SELECT COUNT(*) FROM @Sample AS s2 WHERE s2.Region = s1.Region AND s2.Qty <= s1.Qty) AS RankFROM @Sample AS s1ORDER BY s1.Region, 3-- DescendingSELECT s1.Region, s1.Qty, (SELECT COUNT(*) FROM @Sample AS s2 WHERE s2.Region = s1.Region AND s2.Qty >= s1.Qty) AS RankFROM @Sample AS s1ORDER BY s1.Region, 3 DESC[/code] E 12°55'05.63"N 56°04'39.26" |
|
|
|
|
|
|
|