来自同一查询的借记栏的减去信用额度?

时间:2013-03-01 16:27:29

标签: mysql sql

我有以下查询:

SELECT user_id,SUM(credit)AS cred,SUM(debit)AS deb 来自帐户 WHERE user_id ='35'

我希望减去信用卡的借记并将其显示在一列中或作为变量中的值显示

2 个答案:

答案 0 :(得分:3)

这应该有效,并且可能比做其他两个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 

如果您有多个用户,则可以执行以下操作:

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

答案 1 :(得分:0)

你可以计算同一行的差异

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

更新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