Un enfoque sería usar vistas en línea. Para hacer esto
- Cree una consulta que sume los puntos ganados
- Cree una consulta que sume los puntos gastados
- Unir las consultas juntas (una combinación izquierda en caso de que no hayan gastado nada todavía)
- Haz tu resta
SELECT SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM
(
SELECT SUM(Points) AS Points, Recipient_ID
FROM transactions
WHERE Recipient_ID= 137642
GROUP BY Recipient_ID
) AS SumOfPointsEarned
LEFT JOIN
(
SELECT purchases.Student_ID, SUM(rewards.Cost_to_User) AS Points
FROM purchases
INNER JOIN rewards
ON purchases.Reward_ID = rewards.Reward_ID
WHERE Student_ID = 137642
GROUP BY purchases.Student_ID
) AS SumOfPointsOfPurchasesMade
ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID