首页 > 解决方案 > 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 实现这一目标?

标签: 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

推荐阅读