我有以下查询:
SELECT user_id,SUM(credit)AS cred,SUM(debit)AS deb 来自帐户 WHERE user_id ='35'
我希望减去信用卡的借记并将其显示在一列中或作为变量中的值显示
答案 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
答案 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