我有以下表格:
交易:Transaction_ID
Datetime
Giver_ID
Recipient_ID
Points
Category_ID
Reason
奖励:Reward_ID
Title
Description
Image_URL
Date_Inactive
Stock_Count
Cost_to_User
{{1 }}
购买:Cost_to_System
Purchase_ID
Datetime
Reward_ID
Quantity
Student_ID
Student_Name
{{1 }}
工作人员通过积分奖励学生,这将成为交易表的一个条目,如下所示:
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
我的问题是:
鉴于Reward_ID和Student_ID,如果学生有足够的积分购买奖励,我可以用什么SQL语句来计算?
我以前在PHP中做过这个,但是如果可能的话,我希望能够使用单个SQL语句来完成它。伪代码就像100
,但我完全不知道如何去做!
任何建议都将不胜感激。
答案 0 :(得分:1)
一种方法是使用内联视图。要做到这一点
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
答案 1 :(得分:0)
交易:Transaction_ID日期时间Giver_ID收件人_ID点数Category_ID原因
奖励:Reward_ID标题说明Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
购买:Purchase_ID日期时间奖励_ID数量Student_ID Student_Name Date_DealtWith Date_Collected
SELECT SUM(a.Points)来自事务a的Total_Points,b.Reward_ID,b.Student_ID,b.Student_Name 内部加入购买b ON a.Student_ID = b.Student_ID;
这应该是一个表,插入points_table然后你可以使用WHERE Total_Points>加入奖励表。 Cost_to_User ...