I have a Reward System based on MySQL/PHP. Teachers award students points; students can then purchase rewards using their accrued points.
What I’d like to do is display a single percentage figure of students who have purchased rewards.
This sounds quite simple, but in practice it may be a little bit more complicated to achieve.
- I don’t have a list of students in the database, I simply have
transactions - If a student has received a point, their
IDwill be displayed in thetransactionstable under theRecipient_IDcolumn
The transactions table looks like: Transaction_ID, Datetime, Giver_ID, Recipient_ID, Points, Category_ID, Reason.
The purchases table looks like: Purchase_ID, Datetime, Reward_ID, Quantity, Student_ID, Student_Name (blank), Date_DealtWith, Date_Collected
So, for example, I can list all of my student IDs using SELECT DISTINCT Recipient_ID.
FROM transactions
All I basically need is:
- [students] A count of students with a point+ (i.e.
Recipient_IDintransactions) - [purchases] A count of students with a purchase+ (i.e.
Student_IDin `purchases) - [purchases] / [students] * 100
.. but I’m not sure how to do that in one query!
EDIT: Insert Statements*
purchases…
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);
transactions…
INSERT INTO `transactions` (`Transaction_ID`, `Datetime`, `Giver_ID`, `Recipient_ID`, `Points`, `Category_ID`, `Reason`) VALUES
(1, '2011-09-07', 36754, 34401, 5, 6, 'Gave excellent feedback on the new student notebook'),
(2, '2011-09-07', 34972, 137615, 10, 9, 'Helping TG'),
(6, '2011-09-07', 35006, 90185, 2, 1, '');
Here’s an ugly version, which manages to avoid doing the count of students from
transactionstwice through a hackish join between 2 sub-queries.Another version, I’m not certain will work without a
FROMclause in the sub-query – I can’t remember if MySQL will permit this: