总和案例查询时

时间:2013-10-17 12:10:35

标签: sql-server

这是一般的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      

提前感谢任何建议。

3 个答案:

答案 0 :(得分:3)

您可以使用CASE构造来区分借记和贷记条目。

SELECT   account, SUM (amount * CASE type WHEN 'credit' THEN 1 ELSE -1 END)
FROM     my_table
GROUP BY account

答案 1 :(得分: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

答案 2 :(得分:0)

sum(amount * case when type = 'debit' then -1 else 1 end)