使用條件彙總:
SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0
END) as income,
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0
END) as balance
FROM transaction;
如果你仍然想的區別,那麼你需要重複的邏輯:
SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0
END) as income,
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0
END) as expense,
(SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0 END) -
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0 END)
) as balance
FROM transaction;
編輯:
其實,這是最好的共同條件分解出爲WHERE
條款:
SELECT SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN type = '2' THEN amount ELSE 0 END) as expense,
(SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) -
SUM(CASE WHEN type = '2' THEN amount ELSE 0 END)
) as balance
FROM transaction
WHERE state = 'a' AND type IN ('1', '2');
這可以在transaction(state, type, amount)
採取指數的優勢。
你對此很敏感,謝謝。 – Relm