gpt4 book ai didi

python - django 可以支持按某些列分组同时对其他列求和吗

转载 作者:太空狗 更新时间:2023-10-30 02:34:58 25 4
gpt4 key购买 nike

就像下面的查询:

select sum(T.a), sum(T.b) from Table T group by T.c , T.d

django 有什么方法支持这种查询吗?

最佳答案

这很接近:

class Test(models.Model):                                                                                          
class Meta:
app_label = 'ignore'
db_table = 'T'
a = models.IntegerField()
b = models.IntegerField()
c = models.IntegerField()
d = models.IntegerField()

result = Test.objects.values('c', 'd').annotate(Sum('a'), Sum('b'))
print str(result.query)

结果:

SELECT "T"."c", "T"."d", SUM("T"."a") AS "a_sum", SUM("T"."b") AS "b_sum" FROM "T" GROUP BY "T"."c", "T"."d", "T"."c", "T"."d"

为什么 GROUP BY 值会重复,我不知道...

关于python - django 可以支持按某些列分组同时对其他列求和吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5507982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com