[英]MySQL query using CONCAT
我有兩個表:
categories
=> Category_ID
, Title
, Description
, Default_Points
, Groups
transactions
=> Transaction_ID
, Datetime
, Giver_ID
, Recipient_ID
, Points
, Category_ID
, Reason
教師獎勵積分,選擇一個類別(例如“積極態度和行為”)和一個理由(例如“今天的出色工作”)將其輸入transactions
表。
典型的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, '');
典型的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');
我想使用MySQL嘗試做的是產生一個總分列表(即EACH類別的SUM(transactions.Points)
,還有一些示例Reasons
。
我想這將不得不使用CONCAT?
我需要:
SUM(transactions.Points)
categories.title
transactions.reason
每個類別的原因 這可能看起來像...
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!
這可能嗎?
提前致謝,
您要的是GROUP_CONCAT
。
您需要執行以下操作:
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
感謝@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.