来自同一表的不同总和查询并将其联接 [英] Different sum query from same table and join them

查看:53
本文介绍了来自同一表的不同总和查询并将其联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一张表中有两个查询

I have two query from same table

SELECT userId,SUM(amount) AS totalDeposite FROM trx GROUP BY userId

输出:

userId totalDeposite

userId totalDeposite

 1   470
 2   30

查询

SELECT userId,SUM(amount) AS totalFine FROM trx WHERE TYPE='fine' GROUP BY userId

输出:

userId totalFine

userId totalFine

 1    20
 2    30

我如何获得像这样的结果

How can i get the result like

userId totalDeposite  totalFine
1       470           20
2       30            30

推荐答案

尝试如下使用case

SELECT userId,
       SUM(case when TYPE='fine' then amount else 0 end) as totalFine, 
       SUM(amount) AS totalDeposite
FROM trx 
GROUP BY userId

这篇关于来自同一表的不同总和查询并将其联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆