2013-10-17 98 views
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  

在此先感謝您的任何建議。

回答

3

您可以使用CASE構造來區分借記和貸記條目。

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

謝謝Murenik,我瞭解這裏的邏輯。 – user1773949

0
sum(amount * case when type = 'debit' then -1 else 1 end) 
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 
+0

不應該是b.Credits - a.Debits? – ForkandBeard

+0

@ForkandBeard。是 – neelsg