2013-03-01 67 views

回答

0

的值就可以計算出在同一行中的差

SELECT user_id, 
     SUM(credit) AS cred, 
     SUM(debit) AS deb, 
     SUM(credit) - SUM(debit) total 
FROM account 
WHERE user_id = 35 

UPDATE 1

SELECT user_id, 
     SUM(credit) AS cred, 
     SUM(debit) AS deb, 
     SUM(credit) - SUM(debit) total 
FROM account 
WHERE user_id IN (30,31,32,33,34,35) 
GROUP BY user_ID 

更新2

SELECT user_id, 
     SUM(credit) AS cred, 
     SUM(debit) AS deb, 
     SUM(credit) - SUM(debit) total 
FROM account 
WHERE user_id IN (30,31,32,33,34,35) 
GROUP BY user_ID 
HAVING (SUM(credit) - SUM(debit)) < 10 
+0

如果我有不同的用戶ID,所以我應該把像USER_ID = '30,31,32,33,34,35' 等...... – Akaash 2013-03-01 16:31:04

+0

@Akaash然後你可以使用什麼帶有「GROUP BY」的「IN」。看到我的答案。 – Kermit 2013-03-01 16:31:31

+0

@Akaash使用'GROUP BY'和'IN',我更新答案。 – 2013-03-01 16:32:05

3

這應該工作,並很可能略快於做其他兩種SUM小號

SELECT a.user_id, 
     a.cred, 
     a.deb, 
     a.deb - a.cred AS value 
FROM (SELECT user_id, 
       Sum(credit) AS cred, 
       Sum(debit) AS deb 
     FROM account 
     WHERE user_id = '35') a 

如果你有多個用戶,你可以這樣做如:

SELECT a.user_id, 
     a.cred, 
     a.deb, 
     a.deb - a.cred AS value 
FROM (SELECT user_id, 
       Sum(credit) AS cred, 
       Sum(debit) AS deb 
     FROM account 
     WHERE user_id IN (35, 36, 39) 
     GROUP BY user_id) a 

See the demo