我在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)。看起来脚本在对前 2 只股票进行排序后停止了,然后出现了不匹配的符号......
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;