我有以下查询:
SELECT user_id, SUM( credit ) AS cred, SUM( debit ) AS deb FROM account WHERE user_id = '35'
我想从贷方中减去借方并将其显示在一列中或作为变量中的值
这应该可以工作,并且可能比其他两个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
您可以计算同一行中的差异
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