MySQL在select语句中多次求和,取决于不同字段中的布尔值

时间:2017-03-03 12:05:23

标签: mysql sum

为什么这个查询没有给我正确的总数?

     Select H.AccountNo,IF(G.Credit=0,SUM(F.Charge),NULL) AS Debits,IF(G.Credit=1,SUM(F.Charge),NULL) AS Credits
     from transdetails F
       left join transhead G on F.Transhead=G.Seqno
       left join Accounts H on H.SeqNo=G.Account
     Group by H.AccountNo

我正在尝试列出帐户的费用以及单行付款,费用和付款之间的唯一区别是字段Credits,它是布尔值1或0

仍然没有给我正确的价值,因为我知道有账户000223的付款因此,积分不能为0

    H.Accounts  Debits     Credits
    000221      131.00     NULL
    000222      287.70     NULL
    000223      70980.20   NULL
    000224      13280.42   NULL

1 个答案:

答案 0 :(得分:1)

试试这个

 Select H.AccountNo,SUM(IF(G.Credit=0,F.Charge,0)) AS Debits,SUM(IF(G.Credit=1,F.Charge,0)) AS Credits
 from transdetails F
 left join transhead G on F.Transhead=G.Seqno
 left join Accounts H on H.SeqNo=G.Account
 Group by H.AccountNo