MySQL具有组和总和的多个值

时间:2013-05-28 13:52:04

标签: mysql

我有这样的表:

ID    CHANNEL  PRODUCT  VNAME         qty
1     MCN      zynga    zynga v10     100
2     AGN      zynga    zynga v10     100
3     WAR      zynga    zynga v10     200
4     WWW      zynga    zynga v10     250
5     MCN      capple   capple v52    700
6     AGN      capple   capple v52    100
7     WAR      capple   capple v52    200
8     MCN      zynga    zynga v21     50
9     AGN      zynga    zynga v21     30
10    WAR      zynga    zynga v21     20

我需要查询来生成这样的结果:

ID    PRODUCT    MCN    AGN    WAR   WWW
1     zynga      150    139    220   270
2     capple     700    100    200   0

注意:MCN,AGN,WAR,WWW值来自数值的总和

1 个答案:

答案 0 :(得分:-1)

除了使用group by with product之外,还可以使用聚合函数,特别是SUM(IF())函数的组合来解决此问题。

使用准备语句的动态方法

感谢AshReva发表评论,链接到mysql pivot/crosstab query

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(IF(CHANNEL="',
      channel,
      '",qty,0)) as ',
      channel
    )
  ) INTO @sql
FROM prod;


SET @sql = CONCAT('SELECT product, ', @sql, ' 
                  FROM prod 
                  GROUP BY product');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQL小提琴:http://www.sqlfiddle.com/#!2/ed185/5

解决此问题的非动态方式......

select PRODUCT, 
SUM(IF(CHANNEL="MCN", qty, 0)) as MCN,
SUM(IF(CHANNEL="AGN", qty, 0)) as AGN,
etc...
from PRODUCTS
GROUP by PRODUCT;

SQL小提琴:http://www.sqlfiddle.com/#!2/ed185/2