如何对带注释的查询中的数据求和
How to sum data from an annotated query
我正在尝试创建一个报告,按小时显示给定日期内的男性人数、女性人数和总顾客人数。
只要有人进入建筑物,数据就会作为交易插入数据库。它将他们的性别存储在那里。
收集数据的查询如下所示:
initial_query = EventTransactions.objects.using('reportsdb')
.filter(building_id=id,
actualdatetime__lte=end_date,
actualdatetime__gte=beg_date)
从那里,我注释查询以提取日期:
ordered_query = initial_query.annotate(
year=ExtractYear('actualdatetime'),
month=ExtractMonth('actualdatetime'),
day=ExtractDay('actualdatetime'),
hour=ExtractHour('actualdatetime'),
male=Coalesce(Sum(Case(When(customer_gender='M', then=1)), output_field=IntegerField()), Value(0)),
female=Coalesce(Sum(Case(When(customer_gender='F', then=1)), output_field=IntegerField()), Value(0))
).values(
'year', 'month', 'day', 'hour', 'male', 'female'
)
那我怎么按小时对男顾客和女顾客求和呢?
我的意思是我希望向用户提供一个 table,其中包含一天中的每个小时(此时可以是 0-23 之间的数字),该用户的男性总数小时、该小时的女性总数和该小时的顾客总数:
TIME | MALE | FEMALE | TOTAL
0 12 4 16
1 5 8 13
2 2 3 5
3 20 38 58
etc.
如有必要,我很乐意提供更多信息。谢谢!
你快到了。在调用值后对性别人群进行注释,以便数据库将对一组日期时间提取的值进行聚合。
ordered_query = initial_query.annotate(
year=ExtractYear('actualdatetime'),
month=ExtractMonth('actualdatetime'),
day=ExtractDay('actualdatetime'),
hour=ExtractHour('actualdatetime'),
).values(
'year', 'month', 'day', 'hour',
).annotate(
male=Coalesce(Sum(Case(When(customer_gender='M', then=1)), output_field=IntegerField()), Value(0)),
female=Coalesce(Sum(Case(When(customer_gender='F', then=1)), output_field=IntegerField()), Value(0))
)
我正在尝试创建一个报告,按小时显示给定日期内的男性人数、女性人数和总顾客人数。
只要有人进入建筑物,数据就会作为交易插入数据库。它将他们的性别存储在那里。
收集数据的查询如下所示:
initial_query = EventTransactions.objects.using('reportsdb')
.filter(building_id=id,
actualdatetime__lte=end_date,
actualdatetime__gte=beg_date)
从那里,我注释查询以提取日期:
ordered_query = initial_query.annotate(
year=ExtractYear('actualdatetime'),
month=ExtractMonth('actualdatetime'),
day=ExtractDay('actualdatetime'),
hour=ExtractHour('actualdatetime'),
male=Coalesce(Sum(Case(When(customer_gender='M', then=1)), output_field=IntegerField()), Value(0)),
female=Coalesce(Sum(Case(When(customer_gender='F', then=1)), output_field=IntegerField()), Value(0))
).values(
'year', 'month', 'day', 'hour', 'male', 'female'
)
那我怎么按小时对男顾客和女顾客求和呢?
我的意思是我希望向用户提供一个 table,其中包含一天中的每个小时(此时可以是 0-23 之间的数字),该用户的男性总数小时、该小时的女性总数和该小时的顾客总数:
TIME | MALE | FEMALE | TOTAL
0 12 4 16
1 5 8 13
2 2 3 5
3 20 38 58
etc.
如有必要,我很乐意提供更多信息。谢谢!
你快到了。在调用值后对性别人群进行注释,以便数据库将对一组日期时间提取的值进行聚合。
ordered_query = initial_query.annotate(
year=ExtractYear('actualdatetime'),
month=ExtractMonth('actualdatetime'),
day=ExtractDay('actualdatetime'),
hour=ExtractHour('actualdatetime'),
).values(
'year', 'month', 'day', 'hour',
).annotate(
male=Coalesce(Sum(Case(When(customer_gender='M', then=1)), output_field=IntegerField()), Value(0)),
female=Coalesce(Sum(Case(When(customer_gender='F', then=1)), output_field=IntegerField()), Value(0))
)