我有一个项目表(如下所示)
+------+--------+-------+-----------+-----------+--------+ | prod | period | group | item_code | prop_code | value | +------+--------+-------+-----------+-----------+--------+ | 3 | 199901 | 1 | 101 | 1 | 16240 | | 3 | 199902 | 2 | 102 | 2 | 6142 | | 3 | 199903 | 1 | 105 | 3 | 340 | | 3 | 199904 | 1 | 106 | 4 | 5003 | | 3 | 199905 | 1 | 201 | 5 | 3544 | | 3 | 199906 | 1 | 202 | 6 | 13 | | 3 | 199907 | 1 | 206 | 7 | 9 | | 3 | 199908 | 1 | 301 | 8 | 64 | | 3 | 199909 | 2 | 302 | 9 | 30408 | | 3 | 199910 | 2 | 303 | 10 | 740 | | 3 | 199911 | 1 | 304 | 11 | 660 | | 3 | 199912 | 1 | 305 | 12 | 1113 | | 4 | 200001 | 1 | 306 | 13 | 298881 | | 4 | 200002 | 2 | 307 | 14 | 186097 | | 4 | 200003 | 1 | 402 | 15 | 600 | | 4 | 200004 | 2 | 403 | 16 | 164765 | | 4 | 200005 | 2 | 404 | 17 | 203938 | | 4 | 200006 | 2 | 405 | 18 | 195 | | 4 | 200007 | 1 | 406 | 19 | 80 | | 4 | 200008 | 2 | 409 | 20 | 970 | | 4 | 200009 | 1 | 502 | 21 | 89012 | | 4 | 200010 | 1 | 602 | 22 | 47473 | | 4 | 200011 | 2 | 603 | 23 | 775 | | 4 | 200012 | 1 | 604 | 24 | 335 | +------+--------+-------+-----------+-----------+--------+
我正在尝试动态地将行更改为“#period; period'将列在列和各自的值#39;将会在'期间?像这样 -
| prod | group | item_code | prop_code | 199901 | 199902 | 199903 | 199904 | 199905 | 199906 | 199907 | 199908 | 199909 | 199910 | 199911 | 199912 | 200001 | 200002 | 200003 | 200004 | 200005 | 200006 | 200007 | 200008 | 200009 | 200010 | 200011 | 200012 |
非常感谢任何帮助。
答案 0 :(得分:0)
看起来你已经遇到了GROUP_CONCAT的最大长度,长度为1024个字符。
您可以使用此SET SESSION group_concat_max_len
来增加其长度
SET SESSION group_concat_max_len = 1000000;
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'MAX(CASE WHEN period = ', period, ' then value ELSE NULL end) AS period', period, '') ) INTO @sql FROM items;
SET @sql = CONCAT('SELECT prod,`group`,item_code,prop_code, ', @sql, ' FROM items GROUP BY prod,`group`,item_code,prop_code');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;