1

我有以下查询:

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

我想从贷方中减去借方并将其显示在一列中或作为变量中的值

4

2 回答 2

3

这应该可以工作,并且可能比其他两个SUMs稍微快一点

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 

查看演示

于 2013-03-01T16:28:56.610 回答
1

您可以计算同一行中的差异

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
于 2013-03-01T16:28:40.280 回答