mysql - 如何从同一张表中查询同一列但条件不同的两个不同的 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)
但我没有得到预期的结果......我得到的非活动用户的数量与非活动用户的数量相同。
解决方案
您可以使用条件聚合:
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中只有0
s 和s ,我们可以简化:1
active
select
sum(active * total) total_active,
sum( (1 - active) * total) total_inactive
from mytable
推荐阅读
- python - 对 x 轴的值进行排序,以便在计算 f(x) 时均匀地填充绘图 f(x)
- javascript - 如何让 Underscore 表现得像 Ramda?
- python - 使用需要编码的moviepy向视频添加字幕
- angular - Angular 将冒号放在 HTML 元素之外
- spring-mvc - Saml 2.0 与 Spring MVC ui Extjs 的集成
- sql - 编辑 GeoJSON 解析代码以在 SQL 中解析 JSON 代码
- laravel - 发送事件时出错 - laravel websocket ssl
- swift - AppClip 如何从 URL 中获取查询项
- java - ResponseEntity 不接受文本/csv:SpringBoot
- amazon-web-services - AWS S3 + Cloudfront URL 验证 (CORS?)