私は次のテーブルを持っています:
トランザクション: Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
報酬: Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
購入:Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name Date_DealtWith Date_Collected
スタッフは、次のように、トランザクションテーブルへのエントリとなるポイントを学生に与えます。
Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
8 2011-09-07 36761 127963 2 1 Excellent behaviour in behaviour unit
その後、学生は次のように購入テーブルへのエントリとなる報酬を購入できます。
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
すべての報酬は、報酬データベーステーブルに手動で保存されます。
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
私の質問はこれです:
学生名、獲得ポイント、消費ポイント、残りポイントを返すために使用できるSQLステートメントは何ですか?
私はしばらく前に同様の質問をしましたが、それは次のステートメントを提供しました。ただし、検査の結果、完全に正確であるとは限りません。具体的には、使用済みポイントが正しく機能していません。
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
前もって感謝します、