2014-10-06 74 views
0

表统计MySQL的结合两种选择命令 - 沁和集团通过

**Season Owner Week Points Comment** 
2013  A  1  5  Excellent 
2013  A  2  9  Bad 
2013  B  1  4  Ok 
2013  B  2  5  Good 

我试图得到以下结果(如下图),从表(以上)使用MySQL查询。我想显示最新一周的评论和总分。

Season Owner Points Comment 
2013  A  14  Bad 
2013  B  9  Good 

以下(下)给了我正确的分组和总数,但评论不是来自最新的一周。想法?

Select Owner, sum(Points), Comment FROM Standings WHERE Season=2014 GROUP BY Owner 

回答

0

我会用substring_index()/group_concat()方法:

Select Owner, sum(Points), 
     substring_index(group_concat(Comment order by week desc), ',', 1) as LastComment 
FROM Standings 
WHERE Season = 2014 
GROUP BY Owner ; 
+0

完美!正是我需要的。 – JD7 2014-10-06 01:14:17

1

看起来像旧案例CONCAT-MAX-SUBSTR诡计!

SELECT 
    Season, Owner, 
    SUM(Points) AS Points, 
    SUBSTR(MAX(CONCAT(LPAD(WEEK, 5, '0'),Comment)),6,100) AS Comment 
FROM standings 
GROUP BY Season, Owner 

SQLfiddle

+0

感谢您的帮助!这工作,但我有多个赛季在表(我可能不清楚)。 – JD7 2014-10-06 01:13:32