Mysql垂直组合2列(不要求concat)

时间:2014-06-15 04:06:28

标签: mysql sql

我有一张包含2个cols的表:

category count
x0         10
x1         20
x2         30
x3         40

我想将category x1x3合并为x1,将相应的count值合并为(20 +40 =60) < / p>

所需的结果如下:

category count
x0         10
x1         60
x2         30

2 个答案:

答案 0 :(得分:3)

UPDATE `table` 
SET `count` = ( SELECT * 
                FROM ( SELECT SUM(`count`) 
                       FROM `table` 
                       WHERE `category` IN ('x1','x3') 
                     ) x
              ) 
WHERE `category` = 'x1';

DELETE FROM `table` 
WHERE `category` = 'x3';

SQLFiddle

答案 1 :(得分:2)

SELECT IF(category = 'x3', 'x1', category) AS adjusted_category
     , SUM(count) AS `count` 
FROM ... 
GROUP BY adjusted_category

编辑:已修复。