首页 > 解决方案 > Django,Postgresql 按月聚合函数也使用年份

问题描述

我有一个数据库表,其中包含 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() 方法,我得到了与上面相同的结果。所以计数是正确的。

为什么这行得通?有一个更好的方法吗?

标签: djangopostgresqlaggregation

解决方案


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

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

print(qs.query)

推荐阅读