doukun0888 2013-11-05 02:44
浏览 137
已采纳

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

This is the structure of my table: enter image description here

Then I run a query

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'

and get a table like

enter image description here

How can I convert "index_name" rows to columns like:

date | MSCI EAFE Mid NR USD | Alerian MLP PR USD etc

enter image description here

In other words I need each column to represent an index and rows to represent date-result. I understand that MySQL doesn't have pivot table functions. What is the easiest way of doing this?

I've tried this code, but it generates an error:

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

I need to make the conversion on the query level - not PHP. Please suggest a nice and elegant solution. Thanks!

  • 写回答

1条回答 默认 最新

  • douyinliu8813 2013-11-05 03:51
    关注

    Try

    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
    

    Sample output:

    |       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 |
    ...
    

    Here is SQLFiddle demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?