我正在使用此代码聚合数据库中的行:
from django.db.models import Avg
from django.db.models import FloatField
query_set=testTable.objects.filter(location='TgR',\
part__in=['Q', 'F'],week_number__lte=38,week_number__gte=42).\
annotate(col1_avg=Avg('col1'),col2_avg=Avg('col2'),col3_avg=Avg('col3'),\
Total= (Avg('col1',output_field=FloatField())+Avg('col2', output_field=FloatField())+Avg('col3', output_field=FloatField()))
)
原始查询如下所示:
SELECT week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total
FROM table1
WHERE location = 'TgR'
AND week_number BETWEEN 38 AND 42
AND part IN ('Q', 'F')
GROUP BY 1 ,2 ,3;
我想将其更改为:
SELECT YEAR(date), week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total
FROM table1
WHERE location = 'TgR'
AND week_number BETWEEN 38 AND 42
AND part IN ('Q', 'F')
GROUP BY 1,2,3,4;
基本上我想要做的就是将那一年添加到聚合中,但不知道如何做到这一点。
提前致谢,
答案 0 :(得分:1)
django有关于聚合的整个部分和概念。
https://docs.djangoproject.com/en/1.11/topics/db/aggregation/