简体   繁体   English

使用CONCAT的MySQL查询

[英]MySQL query using CONCAT

I have two tables: 我有两个表:

categories => Category_ID , Title , Description , Default_Points , Groups categories => Category_IDTitleDescriptionDefault_PointsGroups

transactions => Transaction_ID , Datetime , Giver_ID , Recipient_ID , Points , Category_ID , Reason transactions => Transaction_IDDatetimeGiver_IDRecipient_IDPointsCategory_IDReason

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. 教师奖励积分,选择一个类别(例如“积极态度和行为”)和一个理由(例如“今天的出色工作”)将其输入transactions表。

A typical categories row may be: 典型的categories行可能是:

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: 典型的transactions行可能是:

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. 我想使用MySQL尝试做的是产生一个总分列表(即EACH类别的SUM(transactions.Points) ,还有一些示例Reasons

I'd imagine this will have to use a CONCAT? 我想这将不得不使用CONCAT?

I need: 我需要:

  • SUM(transactions.Points) per category 每个类别的SUM(transactions.Points)
  • categories.title
  • 5 unique transactions.reason per category 5个独特的transactions.reason每个类别的原因

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. 您要的是GROUP_CONCAT

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: 感谢@ChrisPatrick的回答,这是我使用的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM