首页 > 解决方案 > 如何从同一张表中查询同一列但条件不同的两个不同的 Sum?

问题描述

我想获取活跃用户的字段总和和非活跃用户的字段总和。

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

期望是结果 activeTotal = 15 和 InactiveTotal = 50 的查询

SELECT SUM(actUser.total) as activeTotal, SUM(inActUser.total) as inactiveTotal FROM user actUser JOIN user inActUser ON inActUser.id = inActUser.id WHERE (actUser.active = 1 AND actUser.userId = 1) OR (inActUser.活动 = 0 AND inActUser.userId= 1)

但我没有得到预期的结果......我得到的非活动用户的数量与非活动用户的数量相同。

标签: mysqlsqlsumpivotcase

解决方案


您可以使用条件聚合:

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

如果您在 column中只有0s 和s ,我们可以简化:1active

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

推荐阅读