【问题标题】:MYSQL Group By Query with subtract of number based on where conditionMYSQL Group By Query,根据where条件减去数字
【发布时间】:2021-05-19 06:59:38
【问题描述】:

我有一个事务表(“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

【问题讨论】:

  • 请提供样本数据和所需结果。

标签: mysql sql group-by


【解决方案1】:

我怀疑你想要条件聚合:

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

【讨论】:

  • @Gordon Linoff,工作正常,谢谢
  • 我们是否有可能更新/替换另一个 MySQL 表上的这些点?
  • @Venkatasivaramireddy.Venna。 . .那将是一个不同的问题。当然,您可以在updateinsert 中使用这样的查询。
猜你喜欢
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多