简体   繁体   中英

Count occurrences of values on a single column grouped by week

I'm trying to accomplish this using Django 2.0 ORM, but if you can solve this with a raw SQL query that would be very helpful too.

Say for example I have a table with the column "destination", which will always be the name of a city, such as "Los Angeles", "New York", "San Francisco", or "Seattle" (but we don't know in advance how many different cities there could be).

I need a SQL query (or Django ORM code) that will get me a count of all the cities for a specified date range, grouped by the record's week (based on created_at timestamp, with weeks starting on Mondays).

Here is an example of the Django model (very simple):

from django.db import models
from django.utils import timezone


class Package(models.Model):
    id = models.AutoField(serialize=False, primary_key=True)
    name = models.CharField(max_length=64)
    email = models.CharField(max_length=128, unique=True)
    phone = models.CharField(max_length=32)
    destination = models.CharField(max_length=64)
    created_at = models.DateField(db_index=True, default=timezone.now)
    updated_at = models.DateField(default=timezone.now)

And here is an example of the desired output, structured as JSON:

{
    "2017-06-05-2017-06-11": {
        "Los Angeles": 100,
        "New York": 50,
        "Copenhagen": 20
    },
    "2017-06-12-2017-06-18": {
        "Los Angeles": 10,
        "Toronto": 23,
        "Las Vegas": 21,
        "Carson City": 8,
        "Raleigh": 1
    },
    "2017-06-19-2017-06-25": {
        "Toronto": 24,
        "Tokyo": 75,
        "Kansas City": 123,
        "Salem": 84,
        "Bismarck": 22,
        "Boise": 77,
        "Las Vegas": 123
    }
}

Note that the results can vary in size, the date ranges all start on a Monday and end on a Sunday (both inclusive), and the city names are variable and unknown.

I know there are ways to build this into Python logic and do many queries, but I'm hoping we can do this in a single query. Thanks!

for raw query you could group by an count

select destination, week(created_at,1), count(*)
from my_table
group by destination, week(created_at,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM