SQL:按表分组

时间:2014-12-23 09:20:32

标签: sql postgresql group-by

假设我们使用PostgreSQL并有2个表,departmentemployee,后者属于并且在前者中有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.iddepartment的主键,为什么我还需要按所有其他列进行分组?

1 个答案:

答案 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子句避免了连接列的双重性。