【问题标题】:Django, Postgresql Aggregate By Month Function is Also Using YearDjango,Postgresql 按月聚合函数也使用年份
【发布时间】:2019-09-21 11:12:05
【问题描述】:

我有一个数据库表,其中包含 2 年期间的“票证”。每张票都有一个工作日期。我想逐年计算每个月的票总数(例如 2018 年 1 月与 2019 年 1 月不同)。

当我拼凑查询时,我偶然发现了一些可行的方法,但我不知道为什么。或者,如果查询有意义。这里是:

qs = Ticket.filter(work_date__range=[datetime.date(2018, 1, 1), 
datetime.date.today()]).\
annotate(year=ExtractYear('work_date'), 
month=ExtractMonth('work_date')).\
values('year','month').\
annotate(count=Count('month')).order_by('year', 'month')

给出这个输出:

{'count': 13816, 'year': 2018, 'month': 1},
{'count': 12778, 'year': 2018, 'month': 2}, 
{'count': 13960, 'year': 2018, 'month': 3},
{'count': 14128, 'year': 2018, 'month': 4}, 
{'count': 15277, 'year': 2018, 'month': 5}, 
{'count': 15689, 'year': 2018, 'month': 6}, 
{'count': 14905, 'year': 2018, 'month': 7}, 
{'count': 16025, 'year': 2018, 'month': 8}, 
{'count': 14044, 'year': 2018, 'month': 9}, 
{'count': 16332, 'year': 2018, 'month': 10}, 
{'count': 15397, 'year': 2018, 'month': 11}, 
{'count': 14348, 'year': 2018, 'month': 12}, 
{'count': 17166, 'year': 2019, 'month': 1}, 
{'count': 15504, 'year': 2019, 'month': 2}, 
{'count': 16311, 'year': 2019, 'month': 3}, 
{'count': 14910, 'year': 2019, 'month': 4}, 
{'count': 440, 'year': 2019, 'month': 5}

我的期望是,由于聚合函数仅按“月”计数,例如,所有第 1 个月的计数都相同,而与年份无关。

我按月运行了一个简单的查询并使用了 .count() 方法,我得到了与上面相同的结果。所以计数是正确的。

为什么会这样?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: django postgresql aggregation


    【解决方案1】:

    您可以按年/月组合获得组,因为这些是您的值。如果要按月计算,请将values('year','month') 更改为values('month')

    计数只是您要计数的字段。 您可以改为计算“id”,您将获得相同的数字。 您可以随时查看生成的查询,这可能会让您更清楚。

    print(qs.query)
    

    【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2022-01-14
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多