我正在尝试透视这样创建的mysql表
'CREATE TABLE `fundreturns` (
`Timestamp` datetime NOT NULL,
`FundName` varchar(255) NOT NULL,
`MonthYear` datetime NOT NULL,
`Returns` decimal(9,7) DEFAULT NULL,
PRIMARY KEY (`FundName`,`MonthYear`),
CONSTRAINT `FundName` FOREIGN KEY (`FundName`) REFERENCES `fundnames` (`fund_name`))
所以结果将是一个
Date Company 1 Company 2 ...Company 200
-------------------------------------------------
09/18 {Returns }
07/18
不是每个公司每个月都有一个回报,而且是一个单一的百分比数字,不需要整个月加起来。我一直在寻找使用mysql或php的解决方案,我遇到了关于动态sql语句的答案,并尝试使用
SET @@group_concat_max_len = 32000;
SET @sql_dynamic = (
SELECT
GROUP_CONCAT( DISTINCT
CONCAT(
'IF(fundname = '''
, fundname
, ''', returns, NULL) AS '
, fundname
)
)
FROM fundreturns
);
SET @sql = CONCAT('SELECT monthyear, ',
@sql_dynamic, '
FROM fundreturns
GROUP BY monthyear'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这给了我一个错误
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(ACL) Alternative Fund,IF(fundname = 'ABCA Reversion', fundreturns, NULL) AS ABC' at line 1
我做错什么了?有没有更好的办法?
1条答案
按热度按时间uyto3xhc1#
考虑以下几点。。。
输出: