如何在mysql中透视两个值?

时间:2014-03-10 11:49:21

标签: mysql pivot

我有以下表结构:

+-------+----------+------+------------+------------+
| agent | product  | type | value_2013 | value_2014 |
+-------+----------+------+------------+------------+
| John  | product1 | A    |         10 |         11 |
| John  | product1 | C    |         14 |         13 |
| Mike  | product1 | A    |         11 |         20 |
| Mike  | product2 | C    |         13 |         15 |
+-------+----------+------+------------+------------+

类型始终为A或C. 我需要在像这样的表中转换(pivot)

 agent, product, type, value_2013_A, value_2013_C, value_2014_A, value_2014_C

 ...
 ...

我编写了以下SQL查询,但它不起作用。它只需要第一种类型

SELECT agent,product,
 case when type='C' then value_2013 else 0 end as value_2013_C,   <-- take this value,ok!
 case when type='C' then value_2013 else 0 end as value_2013_A,    <-- but obviously not take this value
 case when type='A' then impap else 0 end as value_2014_A,        <-- take this value, ok!
 case when type='A' then impac else 0 end as value_2014_C          <-- but obviously not take this value
    FROM  mytable 
    GROUP BY agent,product;

如何修改?

1 个答案:

答案 0 :(得分:0)

你忘记了最大化。试试那个

 SELECT agent,product,
 max(case when type='C' then value_2013 else 0 end) as value_2013_C,   
 max(case when type='C' then value_2013 else 0 end) as value_2013_A,    
 max(case when type='A' then impap else 0 end) as value_2014_A,        
 max(case when type='A' then impac else 0 end ) as value_2014_C         
 FROM  mytable 
 GROUP BY agent,product;