我有一个特定的要求,我需要将辅助表中的所有列转换为行以及来自主数据的数据。主表(特许)与辅助表(engineer_details)有一个很多关系然后这些我需要将查询结果导出到Excel工作表[csv文件]。我能够收集数据记录,但无法导出,因为我有来自辅助表的动态数量的列和列名称。我试图将结果插入临时表,但由于第二个表的列动态性,它失败了。我也尝试直接从select导出但由于与excel标题变为动态相同的原因而失败 以下是我用过的代码。请提出解决方案
DELIMITER //
DROP PROCEDURE IF EXISTS datadump //
DROP TABLE IF EXISTS data_dm_table//
CREATE PROCEDURE datadump()
BEGIN
DECLARE tempSQL VARCHAR(21845);
DECLARE pivotCount INT ;
DECLARE packageName VARCHAR (20) ;
DECLARE curCons CURSOR FOR SELECT PACKAGE_NAME FROM concessions;
SET session group_concat_max_len = 100000;
open curCons;
read_loop: LOOP
set pivotCount = pivotCount+1;
FETCH curCons INTO packageName;
SET @enabled = TRUE;
SELECT Concat(
'SELECT business_key, ',
Group_Concat( x SEPARATOR ','),
' FROM engineer_details GROUP BY business_key '
)
INTO tempSQL
FROM (
SELECT Concat('Max( CASE WHEN business_key_id = ''',
business_key_id,
''' THEN Execution_hour END ) As Execution_hour_',business_key_id
) As x
FROM engineer_details where BUSINESS_KEY like concat(packageName,'%')
) x;
IF tempSQL IS NULL THEN
ITERATE read_loop;
END IF;
set tempSQL =concat(' Select * from concessions left join (',
tempSQL, ' ) as temp
on concessions.PACKAGE_NAME = \'', packageName,
'\' and temp.BUSINESS_KEY like concat(concessions.PACKAGE_NAME, \'%\')
GROUP BY business_key ;'
);
IF tempSQL IS NOT NULL THEN
SET @sql=tempSQL;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
set pivotCount =0;
END LOOP;
CLOSE curCons;
END //
添加样本输入和输出。如果您查看包装CN_121017T6和零件号p2对应的数据,则优惠中有3条记录与工程师详细信息相匹配。对于包装名称CN_121017T7和零件号p1的特许权,我们有工程师的详细信息只有一个记录。请查看数据在结果表中的填充方式。