0

我有以下表格:

交易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


我的问题是:
给定一个 Reward_ID 和一个 Student_ID,如果学生有足够的积分来购买奖励,我可以使用什么 SQL 语句来计算?

我以前在 PHP 中做过这个,但如果可能的话,我希望能够使用单个 SQL 语句来做到这一点。伪代码有点像SELECT ( SumOfPointsEarned - SumOfPointsOfPurchasesMade ),但我完全不知道该怎么做!

任何建议将不胜感激。

4

2 回答 2

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
于 2012-05-31T15:03:11.470 回答
0

交易: Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID 原因

奖励 : Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System

购买:Purchase_ID Datetime Reward_ID 数量 Student_ID Student_Name Date_DealtWith Date_Collected


SELECT SUM(a.Points) Total_Points, b.Reward_ID, b.Student_ID, b.Student_Name from transactions a inner join purchase b ON a.Student_ID = b.Student_ID;

这应该是一张表,在 points_table 中插入,然后您可以使用 WHERE Total_Points > Cost_to_User 将其加入奖励表中...

于 2012-05-31T15:03:06.853 回答