mysql - 如何使用 select sum() 按组选择值?
问题描述
我需要按组选择值(从 0 到 10,从 10 到 50,超过 50)。
user_id amount
1 20
1 40
2 5
3 30
3 1
为什么这个查询不能正常工作?
select (select sum(amount)),
case
when (select sum(amount))<10 then '0-10'
when (select sum(amount))>=10 and (select sum(amount))<50 then '10-20'
else '>50' end as total_amount, count(distinct user_id)
from table
group by
case
when (select sum(amount))<10 then '0-10'
when (select sum(amount))>=10 and (select sum(amount))<50 then '10-20'
else '>50' end as total_amount, count(distinct user_id);
output
diapason number_of_users
0-10 1
10-50 1
>50 1
请给我提示
解决方案
您的查询有许多问题,但主要是它不起作用,因为您需要在排序到范围之前按用户进行求和。试试这个:
SELECT CASE
WHEN amount BETWEEN 0 AND 9 THEN ' 0-10'
WHEN amount BETWEEN 10 AND 50 THEN '10-50'
ELSE '>50' END AS diapason,
COUNT(*) AS number_of_users
FROM (SELECT SUM(amount) AS amount
FROM payments
GROUP BY user_id) p
GROUP BY diapason;
输出
diapason number_of_users
0-10 1
10-50 1
>50 1
推荐阅读
- c# - 如何平滑路径边缘的速度
- python - 如何对齐列表内的元组内的元素?
- java - com.google.firebase.database.DatabaseException:无法将 java.lang.String 类型的值转换为 long
- python - 带有 StringProperty() 的 Kivy 标记
- spring-boot - 如何将许多应用程序迁移到 Spring-Boot?策略和指南链接,而不是详细信息
- tcl - Tcl 反斜杠替换不像我想象的那样工作
- javascript - undefined 不是函数(评估'_this.props.navigation.navigate')
- node.js - 从客户端向服务器发送获取请求会导致 404 Next.js Express
- javascript - 创建和测试单个 Javascript 嵌套函数
- java - 如何检查给定的字符串转换为long是否是EpochMills?