简体   繁体   中英

Minus credit from debit column in same query?

I have following Query:

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

I want to minus debit from credit and show it in one column or as a value in a variable

This should work and is probably slightly faster than doing two other SUM s

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 

If you have multiple users, you can do something like:

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

you can calculate the difference in the same line

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

UPDATE 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM