我有一个基于MySQL / PHP的奖励系统。教师授予学生积分;然后学生可以使用累积积分购买奖励。
我想要做的是显示已购买奖励的学生的单个百分比数字。
这听起来很简单,但在实践中可能会有点复杂。
transactions
ID
将显示在transactions
栏下的Recipient_ID
表格中 transactions
表格如下:Transaction_ID
,Datetime
,Giver_ID
,Recipient_ID
,Points
,Category_ID
,{ {1}}。
Reason
表格如下:purchases
,Purchase_ID
,Datetime
,Reward_ID
,Quantity
,Student_ID
(空白) ),Student_Name
,Date_DealtWith
因此,例如,我可以使用Date_Collected
列出我的所有学生ID。
我基本上需要的是:
SELECT DISTINCT Recipient_ID
FROM transactions
中的Recipient_ID
transactions
)..但我不确定如何在一个查询中执行此操作!
编辑:插入语句*
...购买
Student_ID
...交易
INSERT INTO `purchases` (`Purchase_ID`, `Datetime`, `Reward_ID`, `Quantity`, `Student_ID`, `Student_Name`, `Date_DealtWith`, `Date_Collected`) VALUES
(1, '2011-09-27 16:55:16', 1, 1, 34240, '', '2011-09-27 16:55:16', '2011-12-12 15:45:43'),
(2, '2011-09-28 13:02:26', 1, 1, 137636, '', '2011-09-27 16:55:16', '2011-09-27 16:55:16'),
(3, '2011-09-29 11:29:09', 1, 1, 137685, '', NULL, NULL);
答案 0 :(得分:0)
这是一个丑陋的版本,它设法避免通过2个子查询之间的hackish连接从transactions
两次计算学生的数量。
SELECT
numrewards_students,
numpurchase_students,
numpurchase_students / numrewards_students * 100.0
FROM
( SELECT 0 AS joiner, COUNT( DISTINCT Recipient_ID ) AS numrewards_students FROM transactions ) AS trs
JOIN ( SELECT 0 AS joiner, COUNT( DISTINCT Student_ID ) AS numpurchase_students FROM purchases ) AS prs ON trs.joiner = prs.joiner
另一个版本,我不确定在子查询中没有FROM
子句的情况下工作 - 我不记得MySQL是否允许这样做:
SELECT
numrewards_students,
numpurchase_students,
numpurchase_students / numreward_students * 100.0
FROM
(
(SELECT COUNT(DISTINCT) Recpipient_ID AS numrewards_students FROM transactions) AS numrewards_stduents,
(SELECT COUNT(DISTINCT) Student_ID AS numpurchases_students FROM purchases) AS numpurchase_stduents
)