将记录值显示为列

时间:2014-04-17 14:58:34

标签: mysql sql

我有一张这样的表:

    X    |      Y      |  Z
---------+-------------+-----
3136     |   2014-03   |  A
700      |   2014-03   |  B
531      |   2014-03   |  C
1575     |   2014-03   |  D
2776     |   2014-04   |  A
1200     |   2014-04   |  B
148      |   2014-04   |  C
903      |   2014-04   |  D

我希望将此表格转换为:

Date        |  A   |  B   |  C   |  D
------------+------+------+------+------
2014-03     | 3136 | 700  | 531  | 1575
2014-04     | 2776 | 1200 | 148  | 903

如何通过一次选择来完成?

2 个答案:

答案 0 :(得分:3)

SELECT y as Date,
SUM(CASE WHEN Z='A' THEN X ELSE 0 END) as A,
SUM(CASE WHEN Z='B' THEN X ELSE 0 END) as B,
SUM(CASE WHEN Z='C' THEN X ELSE 0 END) as C,
SUM(CASE WHEN Z='D' THEN X ELSE 0 END) as D
FROM table
GROUP BY y

答案 1 :(得分:2)

select 
    Y as date
  , MAX( case Z when 'A' then X else null end ) as `A`
  , MAX( case Z when 'B' then X else null end ) as `B`
  , MAX( case Z when 'C' then X else null end ) as `C`
  , MAX( case Z when 'D' then X else null end ) as `D`
  -- add more if requird
from table_name
group by Y