En tilgang ville være at bruge inline-visninger. For at gøre dette
- Opret en forespørgsel, der summerer de optjente point
- Opret en forespørgsel, der summerer de brugte point
- Sæt forespørgslerne sammen (en venstre joinforbindelse, hvis de ikke har brugt noget endnu)
- Foretag din subtraktion
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