首页 > 解决方案 > MYSQL Group By Query,根据where条件减去数字

问题描述

我有一个事务表(“TableA”),在 TableA 中有这些字段app_id、user_id、points、tr_type、description。所以在事务中有加减tr_type是有的。现在我想根据 tr_type 获取 user_id 的 total_points (points = added-subtract)。为此我需要如何编写 MySQL 查询>

对于类型是添加或子。

所以现在我想要这 3 个字段的 GroupBY --> app_id, user_id, points

标签: mysqlsqlgroup-by

解决方案


我怀疑你想要条件聚合:

select user_id,
       sum(case when tr_type = 'add' then points 
                when tr_type = 'sub' then - points
           end)
from t
group by user_id;

推荐阅读