SQL - 带总和的条件分组

SQL - Conditional Group By Statement With Sum

我有一个 table 员工,我的任务是计算每个分支机构的总体年收入。

table 看起来像这样:

特殊情况是只计算没有自愿员工工作的分支机构的总收入。

首选结果如下所示:

在 SQL 中是否有一种精简的可能性,即在不使用联接和其他 select 语句的帮助下仅对满足这种特殊条件的组求和?

非常感谢!

您可以按如下方式使用 HAVING 子句:

select branch_id, sum(earning) as total_earnings
  from your_Table t
group by branch_id
having count(case when employee_type = 'Voluntary' then 1 end) = 0

您可以使用聚合,并过滤掉至少有一个带有 having 子句的自愿分支:

select branch_id, sum(earnings) as earnings
from earnings_table
group by branch_id
having max(case when employee_type = 'Voluntary' then 1 else 0 end) = 0

一些数据库有更简洁的选项来表达 having 子句。

在 MySQL 或 SQLite 中:

having max(employee_type = 'Voluntary') = 0

在 Postgres 中;

having not bool_or(employee_type = 'Voluntary')