Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Ranking based on a group and column

Status
Not open for further replies.

achick

Programmer
May 23, 2007
66
US
I have a table where I would like to rank based on a group and column. I want to create a rank column for each type based on cdate column as below.
ID Type CDate Rank
1 Pens 5/20/2000 1
2 Pens 4/10/2004 2
3 Pencils 1/2/2000 2
4 Pencils 5/6/1998 1
5 Pencils 6/6/2006 3
6 Crayons 2/1/2000 1
7 Crayons 8/9/2003 2
8 Crayons 8/9/2003 3

The lowest date gets first ranking.
If cdate is same, lowest ID gets the lowest/minimum rank.

Is there an easy way to rank?

 
you may try this:
Code:
SELECT A.ID, A.Type, A.CDate, Count(*) AS Rank
FROM yourTable AS A INNER JOIN yourTable AS B ON A.Type = B.Type AND A.CDate >= B.CDate
GROUP BY A.ID, A.Type, A.CDate


Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thank you so much for the query.

I changed it a little bit to use ID too when creating rank.

Here is my query but what's happening is if they are the same date in a type, the highest ID gets the rank 1 or first rank. I thought the earliest date and lowest ID should get rank1.

SELECT A.ID, A.Type, A.CDate, Count(*) AS Rank
FROM yourTable AS A INNER JOIN yourTable AS B ON A.Type = B.Type AND A.CDate & A.ID <= B.CDate &B.ID
GROUP BY A.ID, A.Type, A.CDate
 
What about simply this ?
Code:
SELECT A.ID, A.Type, A.CDate, Count(*) AS Rank
FROM yourTable AS A INNER JOIN yourTable AS B ON A.Type = B.Type AND A.ID >= B.ID
GROUP BY A.ID, A.Type, A.CDate

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Actually my ids are not in ascending oprder. So I tried this and seesm to be working so far.

SELECT A.ID, A.Type, A.CDate, Count(*) AS Rank
FROM yourTable AS A INNER JOIN yourTable AS B ON A.Type = B.Type AND format(A.CDate,'yyyymmdd') & A.ID >=format(B.CDate,'yyyymmdd') &B.ID
GROUP BY A.ID, A.Type, A.CDate


 
you shouldn't have to do all the formatting and converting of your dates, this should return the same results:

Code:
SELECT A.ID, A.Type, A.CDate, Count(*) AS Rank
FROM yourTable AS A INNER JOIN yourTable AS B ON A.Type = B.Type AND A.CDate & A.ID  >=B.CDate &B.ID
GROUP BY A.ID, A.Type, A.CDate

Leslie

Come join me at New Mexico Linux Fest!
 
I thought it didn't work when I didn't use the format (may be becasue in access they are in date time field). I will check again

Thankyou
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top