MySQL结合两个选择命令 - Sum和Group By

时间:2014-10-06 00:19:48

标签: mysql mysqli phpmyadmin

表格排名

**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 

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ;