I have two tables:
categories
=> Category_ID
, Title
, Description
, Default_Points
, Groups
transactions
=> Transaction_ID
, Datetime
, Giver_ID
, Recipient_ID
, Points
, Category_ID
, Reason
Teachers award points, choosing a category (like "Positive Attitude & Behaviour") and a reason (like "Excellent work today") which puts an entry into the transactions
table.
A typical categories
row may be:
INSERT INTO `categories` (`Category_ID`, `Title`, `Description`, `Default_Points`, `Groups`) VALUES
(17, 'Olympic Values', 'Please clearly state the correct Olympic Value that''s being used currently in the REASON box.', 5, '');
A typical transactions
row may be:
INSERT INTO `transactions` (`Transaction_ID`, `Datetime`, `Giver_ID`, `Recipient_ID`, `Points`, `Category_ID`, `Reason`) VALUES
(50, '2011-09-07', 35023, 90236, 5, 17, 'Excellent work during PE');
What I'd like to try and do using MySQL is produce a list of total points (ie SUM(transactions.Points)
for EACH category, with a few sample Reasons
too.
I'd imagine this will have to use a CONCAT?
I need:
SUM(transactions.Points)
per category categories.title
transactions.reason
per category This might look like...
Points Title Sample
14252 Olympic Values Excellent work in PE!|Great display of friendship|Well done!
15532 Outstanding Effort Amazing work!|Worked so hard|Great piece!
Is this possible?
Thanks in advance,
It's GROUP_CONCAT
you want.
You'll need to do something like this:
SELECT SUM(t.Points),
c.title,
SUBSTRING_INDEX(GROUP_CONCAT(transactions.reasons SEPERATOR '|'), '|', 5)
FROM transactions t JOIN categories c ON (t.Category_ID=c.Category_ID)
GROUP BY c.Category_ID
Thanks to @ChrisPatrick 's answer, this is the code I used:
SELECT
SUM(t.Points) AS Total_Points,
c.Title,
SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT t.reason SEPARATOR '|'), '|', 5) AS Sample_Reasons
FROM
transactions t JOIN categories c ON (t.Category_ID=c.Category_ID)
GROUP BY c.Category_ID
ORDER BY c.Title ASC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.