0

我有这样的表:

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 值取自 qty 值之和

4

1 回答 1

-1

这个问题可以通过聚合函数,特别是 SUM(IF()) 函数的组合来解决,除了使用 group by 和产品。

使用准备好的语句的动态方法

感谢 AshReva 的评论链接到mysql 数据透视表/交叉表查询

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

于 2013-05-28T14:30:04.187 回答