1

这是一个一般的 SQL 问题

我有这张表(简化),贷方为正,借方为负:

Account Amount  Type
--------------------
john    25      credit  
john    45      debit  
john    5       debit  
john    15      credit  
mike    15      credit  

我想要一个看起来像这样的结果,使用单个查询Case When

Account  Total
--------------------
john     -10      
mike     15      

在此先感谢您的任何建议。

4

3 回答 3

3

您可以使用该CASE构造来区分借方和贷方分录。

SELECT   account, SUM (amount * CASE type WHEN 'credit' THEN 1 ELSE -1 END)
FROM     my_table
GROUP BY account
于 2013-10-17T12:12:33.603 回答
1

如果对您更有意义,您还可以尝试以下操作:

SELECT a.Account, b.Credits - a.Debits AS Total FROM
    (SELECT Account, SUM(Amount) AS Debits
        FROM YourTable GROUP BY Account HAVING Type = 'debit'
    ) AS a
    INNER JOIN
    (SELECT Account, SUM(Amount) AS Credits
        FROM YourTable GROUP BY Account HAVING Type = 'credit'
    ) AS b
于 2013-10-17T12:15:23.737 回答
0
sum(amount * case when type = 'debit' then -1 else 1 end)
于 2013-10-17T12:13:21.950 回答