【问题标题】:How query two different Sum from the same table for the same column but with different condition?如何从同一个表中查询同一列但条件不同的两个不同的 Sum?
【发布时间】:2020-08-30 23:54:02
【问题描述】:

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

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 FROM 用户 actUser 加入用户 inActUser ON inActUser.id = inActUser.id WHERE (actUser.active = 1 AND actUser.userId = 1) OR (inActUser.active = 0 AND inActUser.userId= 1)

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

【问题讨论】:

    标签: mysql sql sum pivot case


    【解决方案1】:

    您可以使用条件聚合:

    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
    

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

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

    【讨论】:

    • 谢谢...它帮助我实现了我想要的。
    猜你喜欢
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多