I have the following tables:
transactions : Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
rewards : Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
purchases : Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name Date_DealtWith Date_Collected
Staff members award students with points which becomes an entry into the transactions table, like this:
Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
8 2011-09-07 36761 127963 2 1 Excellent behaviour in behaviour unit
Students can then purchase a reward which becomes an entry into the purchases table, like this:
Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name Date_DealtWith Date_Collected
1570 2012-05-30 12:46:36 2 1 137616 Bradley Richardson NULL NULL
All of the rewards are stored manually in the rewards database table:
Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
1 Lunch Time Queue Pass (month) Beat the queue and get to the hot food early! /user/74/167976.png 2012-04-16 11:50:00 0 100 0
My question is this:
What SQL statement can I use to return Student Name, Points Earned, Points Spent, Points Remaining?
I asked a similar question a while back, which offered the following statement. However, upon inspection, it doesn't appear to be entirely accurate - specifically Points Spent isn't working correctly.
SELECT Recipient_ID AS StudentID,
SumOfPointsOfPurchasesMade.Points AS PurchasesMade,
SumOfPointsEarned.Points AS PointsEarned,
SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM
(
SELECT SUM(Points) AS Points, Recipient_ID
FROM transactions
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
GROUP BY purchases.Student_ID
) AS SumOfPointsOfPurchasesMade
ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID
WHERE SumOfPointsEarned.Points < SumOfPointsOfPurchasesMade.Points
ORDER BY `CurrentPoints` DESC
Thanks in advance,