I have a table with the following sample data:
id user_id rank date_promoted
1 20 firefighter 1991-10-31
2 32 lieutenant 2003-01-03
3 34 firefighter 1990-11-23
4 20 lieutenant 1993-02-03
5 20 captain 2007-05-23
6 46 firefighter 1999-12-03
id is my primary key. user_id is a foreign key back to the users in the auth_user table.
My goal is to create a query that provides a seniority listing by rank. So, for example, to create a query for the rank ‘firefighter’, I would filter by rank for firefighter and order by date_promoted. But my problem is that user_id 20 is no longer a firefighter. He has been promoted to lieutenant and then captain. How do I, in my query, exclude him from the results of a listing of firefighters?
I’ve thought of using ‘exclude’ but that creates AND’s and just filters out the entries for captain and lieutenant for user_id, leaving the entry for firefighter for user_id 20.
I’ve also thought of using Q objects, which allows me to create OR’s. But again, that still leaves a firefighter entry for user_id 20.
I cannot figure out how to identify that user_id 20 has multiple entries and therefore remove him/her from the results for a firefighter listing.
Thanks.
Use numbers for ranks (i. e.
1forfirefighter,2forlieutenantand so on). Then you will easily exclude anyone who is higher (or lower) then desired rank. Or you will be able to select max (min) rank for any user with aggregation.If you don’t want to change your DB schema you can select it with one subquery: