如何按列分组并返回其他列的SUM?

时间:2014-02-13 19:54:26

标签: mysql sql

我按信息ID和ANCHOR选择值:

 SELECT 
      infoid, 
      anchor, 
      value 
 FROM 
      infodata 
 WHERE 
      (infoid = 1) 
      OR (infoid = 2)
      OR (infoid = 3)
 ORDER BY 
      anchor ASC

此查询返回一个infoid,anchors和数字列表:

infoid      anchor     value
------      -----      -----
1           10         500
2           10         600
3           10         700

1           20         800
2           20         900
3           20         1000

如何通过ANCHOR分组并返回3个信息的SUM()值?返回这样的东西:

anchor     value
-----      -----
10         500+600+700
20         800+900+1000

2 个答案:

答案 0 :(得分:6)

您需要使用GROUP BY子句:

SELECT
      anchor, 
      SUM(value) 
 FROM 
      infodata 
 WHERE 
      infoid IN (1,2,3)
 GROUP BY
      anchor
 ORDER BY 
      anchor ASC

答案 1 :(得分:0)

如果您想要与您的结果完全相同,请使用此

SELECT
  anchor, 
  group_CONCAT(value separator '+') value
FROM  infodata 
WHERE infoid in (1,2,3)
GROUP BY anchor
ORDER BY anchor ASC;

结果:

 anchor     value
 -----      -----
 10         500+600+700
 20         800+900+1000