来自同一个表的不同总和查询并加入它们

时间:2015-05-11 06:39:39

标签: sql join

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

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

输出:

userId totalDeposite

 1   470
 2   30

查询

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

输出:

userId totalFine

 1    20
 2    30

我如何得到像

这样的结果
userId totalDeposite  totalFine
1       470           20
2       30            30

2 个答案:

答案 0 :(得分:6)

尝试使用case,如下所示

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

答案 1 :(得分:0)

试试这个

    select * from
    (SELECT userId,SUM(amount) AS totalDeposite FROM trx GROUP BY userId) as tD
    inner join
    (SELECT userId,SUM(amount) AS totalFine FROM trx WHERE TYPE='fine' GROUP BY userId) 
    tF on td.userId = tf.userId