【问题标题】:Query to get column totals and Subtract MySQL查询以获取列总数并减去 MySQL
【发布时间】:2018-09-06 15:14:10
【问题描述】:

我有一个事务表

我可以使用这些查询分别按属性获取所有借方和贷方交易总额

SELECT property, SUM(amount) as creditamount FROM transactions WHERE transactions.type="CREDIT" GROUP BY property    

SELECT property, SUM(amount) as debitamount FROM transactions WHERE transactions.type="DEBIT" GROUP BY property

我很难在一个查询中完成这两个查询,以便我可以减去每行的贷方金额和借方金额并根据属性列出它

我尝试使用子查询,但返回多行。

有什么方法可以实现吗?

【问题讨论】:

    标签: mysql database select transactions subquery


    【解决方案1】:

    条件聚合可能是您正在寻找的。​​p>

    SELECT property, 
     SUM(case when type = 'Credit' then amount else 0 end) as creditamount,
     SUM(case when type = 'Debit' then amount else 0 end) as debitamount,
     SUM(case when type = 'Credit' then amount else 0 end) -
     SUM(case when type = 'Debit' then amount else 0 end) as  diff
     FROM transactions 
     GROUP BY property 
    

    【讨论】:

      【解决方案2】:

      使用自加入

      select debitamount , creditamount
      from (select sum(amount) income
           from  transactions 
           WHERE transactions.type="CREDIT"  
           GROUP BY property) i
      JOIN (select sum(rate) debitamount 
           from transactions 
           WHERE transactions.type="DEBIT" 
           GROUP BY property) e
      

      参考this question

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-02-03
        • 2011-05-09
        相关资源
        最近更新 更多