Django,按月份汇总的Postgresql函数也使用Year

时间:2019-05-02 21:56:32

标签: django postgresql aggregation

我有一个数据库表,其中包含两年内的“门票”。每张票都有一个工作日期。我想逐年统计每个月的门票总数(例如,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()方法,因此得到与上述相同的结果。所以计数是正确的。

为什么这样做?有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

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

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

print(qs.query)