iman453
iman453

Reputation: 9565

Get the 'top' records within every set of records created within 4 days

I'm creating a Django app in which I have a table which has 'items', the dates they were created on, and the number of points they have. I wanted to write a query which returns the items with the most points from the last 4 days, followed by the items with the most points in the 4 days before that, and so on. I was wondering how I can go about doing that (I'm very new to SQL and am very sorry if this is a basic question). I thought I could iterate through getting the top records within every set of 4 in my Django view, and then combine the objects, but that would require me hitting the database for every set, and I'm guessing that would be a bad way of doing it? Any pointers would be really appreciated!

Thanks!

Upvotes: 2

Views: 85

Answers (1)

Greg
Greg

Reputation: 10352

There's no way to avoid hitting the database for every group here, unfortunately. It shouldn't be a big issue though, I'm assuming you'll be limiting the number of groups to something sane? If you're concerned about database load make sure you index your 'date created' and 'points' fields.

Your code should look something like:

from datetime import date, timedelta
from models import Item

groups = []
for i in range(0, 10):
    items = Item.objects.filter(date_created=date.today() - timedelta(i))
    groups.append(items.order_by('-points'))

Upvotes: 5

Related Questions