代码之家  ›  专栏  ›  技术社区  ›  Chuck

Django,Postgresql月聚合函数也使用Year

  •  0
  • Chuck  · 技术社区  · 7 年前

    我有一个数据库表,包含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}
    

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

    为什么这个有用?有更好的方法吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   eran    7 年前

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

    你可以数数“id”而得到相同的数字。

    print(qs.query)