sql如何在Mysql中将行值转换为列?

时间:2017-11-09 15:49:47

标签: mysql database pivot stocks stock-data

我在mysql中获得了大量的库存数据,格式如下......



  date      symbol    open   high   low    close  volume 
2017-11-07  stockA    8.9    8.92   8.88   8.9     68987
2017-11-08  stockA    8.91   8.95   8.9    8.92    98793
2017-11-09  stockA    8.75   8.88   8.71   8.77    99871
2017-11-07  stockB    18.9   18.92  18.88  18.9    12109
2017-11-08  stockB    18.91  18.95  18.9   18.92   11898
2017-11-09  stockB    18.75  18.88  18.71  18.77   10898
2017-11-07  stockC    3.9    3.92    3.88   3.9    98093
2017-11-08  stockC    3.91   3.95    3.9    3.92  109871 
2017-11-09  stockC    3.75   3.88    3.71   3.77  139405 
...




我希望创建一个表格,将数据类型作为行和数据库中的所有股票收集为列:



     date      symbol    open   high   low    close  volume 
    2017-11-07  stockA    8.9    8.92   8.88   8.9     68987
    2017-11-08  stockA    8.91   8.95   8.9    8.92    98793
    2017-11-09  stockA    8.75   8.88   8.71   8.77    99871
    
    2017-11-07  stockB    18.9   18.92  18.88  18.9    12109
    2017-11-08  stockB    18.91  18.95  18.9   18.92   11898
    2017-11-09  stockB    18.75  18.88  18.71  18.77   10898
    
    2017-11-07  stockC    3.9    3.92    3.88   3.9    98093
    2017-11-08  stockC    3.91   3.95    3.9    3.92  109871 
    2017-11-09  stockC    3.75   3.88    3.71   3.77  139405 
    ...

date          type    stockA    stockB   stockC stockD ...
 2017-11-07   open      8.9     18.9     3.9     
 2017-11-08   open      8.92    18.92    3.92
 2017-11-09   open      8.77    18.77    3.77
 2017-11-07   high      8.9     18.92    3.92     
 2017-11-08   high      8.95    18.95    3.95
 2017-11-09   high      8.88    18.88    3.88
 2017-11-07   low       8.88    18.88    3.88     
 2017-11-08   low       8.9     18.9     3.9 
 2017-11-09   low       8.71    18.71    3.71
 2017-11-07   close     8.9     18.9     3.9     
 2017-11-08   close     8.92    18.92    3.92 
 2017-11-09   close     8.77    18.77    3.77
 




我是mysql / sql语法的新手......所以我完全不知道如何做到这一点......有没有人做过类似的事情?

感谢所有链接等。我在阅读链接后尝试用以下脚本解决问题...不知怎的,它抛出了SQL语法错误(错误代码:1064)。在对前两个股票进行排序后,看起来脚本停止了,然后符号不匹配......



SET @sql = NULL;
SELECT 
  GROUP_CONCAT( DISTINCT 
      CONCAT(
        'MAX( if( symbol="',
          symbol,
          '" , open, NULL )) as "',
           symbol, '"' 
         )
      ) INTO @sql
FROM prices ;

SET @sql = CONCAT(' SELECT date, ', @sql, '
          FROM prices');
PREPARE stmt from @sql ;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; 




0 个答案:

没有答案