mysql - MySQL SUM 与 SELECT
问题描述
我有这张桌子叫redeem_points
。这些是用户兑换积分的记录。
id |userId |pointsCollected
-------------------------------
1 12 500
2 12 500
3 12 500
4 34 100
5 34 100
6 56 500
我想生成一个报告,除了这些数据之外,我还想显示收集到的用户的总积分。像这样
id |userId |pointsCollected |totalPointsCollected
--------------------------------------------------
1 12 500 | 1500
2 12 500 | 1500
3 12 500 | 1500
4 34 100 | 200
5 34 100 | 200
6 56 500 | 500
如何使用 MySQL 实现这一目标?
解决方案
一般来说你可以做
select t.*, t2.total
from your_table t
join
(
select userId, sum(pointsCollected) as total
from your_table
group by userId
) t2 on t1.userId = t2.userId
但是使用 MySQL 8+,您可以将其简化为
select *,
sum(pointsCollected) OVER(PARTITION BY userId) AS total
from your_table
推荐阅读
- javascript - 如何将 TradingView Pine 脚本代码转换为 JavaScript?
- r - 在 R 中为孪生数据重塑数据框
- r - 用于模拟的向量
- python - 将值与熊猫中的前一个单元格值进行比较
- wordpress - 在 gulp 安装过程中出现了这个问题
- php - 语法错误,意外的“preg_replace”(T_STRING)
- fluentd - fluentd 将 json 值输出为没有 message_key 的 json
- python - How to applying regex to replace values
- spring - 我收到错误 500,而我正在尝试使用 SpringBoot 显示我的数据库中存在的所有产品
- python - 如何将文件保存到特定文件夹?