SQL Server RANK() function not producing expected result

I'm trying the following query (SQL Server 2008 R2) but not getting the results I expect.
Bad Rank QuerySince I'm partitioning on TowCotnractID and ordering by LogStartTime, I expected the two highlighted rows (same ID) to have a rank of 1 and 2 in descending date time order.  But both have a rank of 1.

Can someone tell me why this is happening and how to fix it?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leo TorresSQL DeveloperCommented:
Each Contract is unique so its 1 for each one. You need to create a partion on what makes each row unique.
Leo TorresSQL DeveloperCommented:
The 2 highlighted rows are not the same they cant be 1 and  2

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike EghtebasDatabase and Application DeveloperCommented:


not rank

Also, you do not need order by at the end.
Jim HornMicrosoft SQL Server Data DudeCommented:
Eyeballeth thy TowContractID values more closely.
Leo is correct in that all TowContractID values in the screenshot are unique.  8668 <> 8688.
Therefore, all RANK(PARTITION BY TowContractID ...) values are 1.
Leo TorresSQL DeveloperCommented:
ops yes good point i am dyslexia I though you were using Row_number().

How ever what I said still remains true you you are partitioning by TowCotnractID each number will generate a partition..

In order to have a 1 and 2 for a TowCotnractID you need this scenerio

ID           date
8668    5/8/2015
8668    5/7/2015

Your Scenario
8668    5/8/2015
8688    5/7/2015

if you partition by ID you will always get a 1 for each
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.