已购买奖励的学生百分比

时间:2012-03-13 16:28:55

标签: mysql

我有一个基于MySQL / PHP的奖励系统。教师授予学生积分;然后学生可以使用累积积分购买奖励。

我想要做的是显示已购买奖励的学生的单个百分比数字

这听起来很简单,但在实践中可能会有点复杂。

  • 我没有数据库中的学生列表,我只是transactions
  • 如果学生收到积分,他们的ID将显示在transactions栏下的Recipient_ID表格中

transactions表格如下:Transaction_IDDatetimeGiver_IDRecipient_IDPointsCategory_ID,{ {1}}。

Reason表格如下:purchasesPurchase_IDDatetimeReward_IDQuantityStudent_ID(空白) ),Student_NameDate_DealtWith

因此,例如,我可以使用Date_Collected列出我的所有学生ID。

我基本上需要的是:

  • [学生]有点+的学生数(SELECT DISTINCT Recipient_ID FROM transactions中的Recipient_ID
  • [购买]购买商品的数量+(即购买时transactions
  • [购买] / [学​​生] * 100

..但我不确定如何在一个查询中执行此操作!


编辑:插入语句*

...购买

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);

1 个答案:

答案 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
)