分组
公司员工表
按照部分分组求平均工资:
SQL语句
select dept,AVG(salary) from employee group by dept;
ORM查询:
from django.db.models import Avg Employee.objects.values("dept"
).annotate(avg=Avg("salary").values(dept, "avg") # 另一个案例:每本书的作者人数:
models.Book.objects.all().annotate(author_num=Count("author")) # 语法 pk字段 ==
主键primary key 模型.objects.values('分组字段').annotate(聚合函数) 模型.objects.values('pk'
).annotate(c=Count('article__title')).values('title','c')
连表分组
SQL语句:
select dept.name,AVG(salary) from employee inner join dept on
(employee.dept_id=dept.id)group by dept_id;
ORM查询:
from django.db.models import Avg models.Dept.objects.annotate(avg=Avg(
"employee__salary")).values("name", "avg")
热门工具 换一换