假设我们使用PostgreSQL并有2个表,department
和employee
,后者属于并且在前者中有FK。
我们现在想要进行汇总选择,我们希望从department
中提取所有信息,然后从employee
汇总一些汇总值:
SELECT d.id, d.name, d.budget, count(*), avg(e.salary), max(e.age), sum(e.children)
FROM department d LEFT JOIN employee e ON e.dept = d.id
GROUP BY d.id, d.name, d.budget
我不喜欢我需要在department
中指定GROUP BY
中的所有列 - 是否可以按照整个表格进行分组"?
还有一点哲学问题,假设我做GROUP BY d.id
。假设d.id
是department
的主键,为什么我还需要按所有其他列进行分组?
答案 0 :(得分:0)
如果employee
预先汇总,则无需列出select
列
select *
from
department d
left join (
select
dept as id,
count(*) as count_employee,
avg(salary) as avg_salary,
max(age) as max_age,
sum(children) as sum_children
from employee
group by dept
) e using (id)
using
子句避免了连接列的双重性。