如何从同一张表中查询同一列但条件不同的两个不同总和?

时间:2020-08-30 23:54:02

标签: mysql sql sum pivot case

我想为活动用户获取字段TOTAL的总和,为不活动用户获取字段TOTAL的总和。

id userId active total
 1 1         1     10
 2 1         1     5
 3 1         0     30
 4 1         0     20

期望的查询将导致activeTotal = 15和InactiveTotal = 50

选择SUM(actUser.total)为activeTotal,SUM(inActUser.total)为inactiveTotal 来自用户actUser JOIN用户inActUser ON inActUser.id = inActUser.id 在哪里(actUser.active = 1 AND actUser.userId = 1)或(inActUser.active = 0 AND inActUser.userId = 1)

但是我没有得到预期的结果。...我获得的闲置用户数与获得闲置用户的数相同。

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select
    sum(case when active = 1 then total else 0 end) total_active,
    sum(case when active = 0 then total else 0 end) total_inactive
from mytable

如果0列中只有1active s,我们可以简化:

select
    sum(active * total) total_active,
    sum( (1 - active) * total) total_inactive
from mytable