【问题标题】:Count multiple columns with group by in one query using Django ORM使用 Django ORM 在一个查询中使用 group by 计算多列
【发布时间】:2019-03-19 05:48:43
【问题描述】:

我有一个表,它有四列(创建、过期、激活、更新),数据类型是 DateTime。我想要每个日期所有四列的计数。

table1.objects.annotate(dt=Truncmonth('created')).values('dt').orderby().annotate(Count('dt'))
table1.objects.annotate(dte=Truncmonth('expires')).values('dte').orderby().annotate(Count('dte'))
table1.objects.annotate(dta=Truncmonth('activated')).values('dta').orderby().annotate(Count('dta'))
table1.objects.annotate(dtr=Truncmonth('renewed')).values('dtr').orderby().annotate(Count('dtr'))

上面是四个不同的查询,它们给了我日期和计数。但我想获取所有列的日期和计数 我想要的是日期 count_dt、count_dte、count_dta、count_dtr。但我得到 date_dt,date_dte,date_dta,date_dtr,count_dt,count_dte,count_dta,count_dtr。 总之,我想把上面的四个查询结合起来。

【问题讨论】:

  • 如果你只是要求我们做你的功课而不表明你已经做了一些努力来解决这个问题,你不会得到答案。请展示你为解决这个问题而编写的 python 代码。顺便说一下,解释一下“合并”是什么意思。总和?
  • 我通过 table.objects.annotate(dt=Truncmonth(col1)).values('dt).orderby().anotate(Count('dt)) 获得单列的结果/跨度>
  • 请给我解决方案
  • 试试table1.objects.annotate(month=Trunc('created', 'month', output_field=DateField())).values('month').annotate(ne=Count('expires')).annotate(na=Count('activated')).annotate(nr=Count('renewed'))。这是假设“创建”涵盖所有月份。否则,您将失去一些月份。
  • 对不起,我上面的评论有误,应该是annotate(ne=Count, na=Count, ...) all in one annotate 子句。请参阅下面的答案。

标签: django django-models orm django-orm


【解决方案1】:

您可以使用 Django 的 Coalesce 函数从所有日期列中选择第一个非空值,然后为每个月份值注释各种计数:

from django.db.models.functions import TruncMonth, Coalesce
from django.db.models import Count    

table1.objects.annotate(month=Coalesce(TruncMonth('created'), TruncMonth('expires'), TruncMonth('activated'), TruncMonth('renewed)))
    .values('month')
    .annotate(nc=Count('created'), ne=Count('expires'), na=Count('activated'), nr=Count('renewed')

输出是一个 QuerySet,其中包含键 month, nc, ne, na, nr 的键值对。

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多