0

I have a table in my Django app, UserMonthScores, where every user has a "score" for every month. So, it looks like

userid | month | year | score
-------+-------+------+------
sil    | 9     | 2014 | 20
sil    | 8     | 2014 | 20
sil    | 7     | 2014 | 20
other  | 9     | 2014 | 100
other  | 8     | 2014 | 1

I'd like to work out which position a specific user was in, for each month, in the ranking table. So in the above, if I ask for monthly ranking positions for user "sil", per month, I should get a response which looks like

month | year | rank
------+------+-----
9       2014   2       # in second position behind user "other" who scored 100
8       2014   1       # in first position ahead user "other" who scored 1
7       2014   1       # in first position because no-one else scored anything!

The way I'd do this in SQL is to join the table to itself on month/year, and select rows where the second table was for the specific user and the first table had a larger score than the second table, group by month/year, and select the count of rows per month/year. That is:

select u1.month,u1.year,count(*) from UserMonthScores u1 
  inner join UserMonthScores u2 
  on u1.month=u2.month and u1.year=u2.year 
  and u2.userid = 'sil' and u1.score >= u2.score 
  group by u1.year, u1.month;

That works excellently. However, I do not understand how to do this query using the Django ORM. There are other questions about joining a table to itself, but they don't seem to cover this use case.

3
  • Do you need to use the ORM? If not you could just use your SQL query as a raw SQL query in django. I'd also suggest changing your SQL to use the RANK() windowing function if your RDMS supports it.
    – cms_mgr
    Sep 3, 2014 at 13:42
  • I don't need to use the ORM, and I have in fact done this by using the raw SQL query above, but it'd be nice to use the ORM if possible because then I'm not circumventing nice things that it does. (Didn't know about RANK -- thank you! -- , but I don't think sqlite supports it anyway.)
    – sil
    Sep 3, 2014 at 14:01
  • I don't think the ORM supports windowing functions but I can only find fairly old references to it. Nonetheless I think your raw SQL probably remains best approach to this.
    – cms_mgr
    Sep 3, 2014 at 14:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.