MySQL数据透视表 - 将行转换为列

时间:2013-11-05 02:44:45

标签: php mysql pivot-table

这是我桌子的结构: enter image description here

然后我运行查询

SELECT `date`,`index_name`,`results` FROM `mst_ind` WHERE `index_name` IN ('MSCI EAFE Mid NR USD', 'Alerian MLP PR USD') AND `time_period`='M1'

并获得类似

的表格

enter image description here

如何将“index_name”行转换为以下列:

日期| MSCI EAFE Mid NR USD | Alerian MLP PR USD

enter image description here

换句话说,我需要每列代表一个索引和行来表示日期结果。我知道MySQL没有数据透视表功能。这样做最简单的方法是什么?

我已尝试过此代码,但会产生错误:

SELECT
  `date`,
  MAX(IF(index_name = 'Alerian MLP PR USD' AND `time_period`='M1', results, NULL)) AS res1,
  MAX(IF(index_name = 'MSCI EAFE Mid NR USD' AND `time_period`='M1', results, NULL)) AS res2
FROM
  `mst_ind`
GROUP BY `date

我需要在查询级别进行转换 - 而不是PHP。请建议一个漂亮而优雅的解决方案。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试

SELECT date,
       MAX(CASE WHEN index_name = 'Alerian MLP PR USD' THEN results END) `Alerian MLP PR USD`,
       MAX(CASE WHEN index_name = 'MSCI EAFE Mid NR USD' THEN results END) `MSCI EAFE Mid NR USD`
  FROM mst_ind
 WHERE index_name IN ('MSCI EAFE Mid NR USD', 'Alerian MLP PR USD') 
   AND time_period = 'M1'
 GROUP BY date

示例输出:

|       DATE | ALERIAN MLP PR USD | MSCI EAFE MID NR USD |
|------------|--------------------|----------------------|
| 1995-01-31 |            -0.0167 |               0.0335 |
| 1995-02-28 |             0.0128 |               0.0409 |
| 1995-03-31 |             0.0464 |               0.0286 |
| 1995-04-28 |             0.0331 |               0.0297 |
| 1995-05-31 |             0.0069 |               0.0398 |
...

这是 SQLFiddle 演示