如何在MySQL中将N列的列透视为行而不使用Union all

xu3bshqb  于 2023-02-28  发布在  Mysql
关注(0)|答案(1)|浏览(132)

我已经浏览了链接(Mysql Convert Column to row (Pivot table ))中的详细信息。由于列的数量很大,并且对所有列使用union all会很耗时。我决定使用给定链接中的最后一个解析。我能够运行查询,结果是:

问题是acct作为数据被包含,而且我想从结果中创建一个表。那么这些条目可以被排除吗?我如何从结果中创建一个表?(SQL新手)

The Code:

SET SESSION group_concat_max_len = 92160;
SET @target_schema='rd';
SET @target_table='pbc_gl';
SET @target_where='`acct`';


SELECT
    GROUP_CONCAT(qry SEPARATOR ' UNION ALL ')
    INTO @sql
FROM (
    SELECT
        CONCAT('SELECT `acct`,', QUOTE(COLUMN_NAME), ' AS `Business_Unit`,`', COLUMN_NAME, '` AS `value` FROM `', @target_table, '` WHERE ', @target_where) qry
    FROM (
        SELECT `COLUMN_NAME` 
        FROM `INFORMATION_SCHEMA`.`COLUMNS` 
        WHERE `TABLE_SCHEMA`=@target_schema 
            AND `TABLE_NAME`=@target_table
    ) AS `A`
) AS `B` ;

PREPARE s FROM @sql;
EXECUTE s; 
DEALLOCATE PREPARE s;
but5z9lq

but5z9lq1#

AND COLUMN_NAME != 'acct'添加到查询的WHERE条件中,以从GROUP_CONCAT()中排除该列。
CREATE TABLE new_table_name连接到查询的开头,使其使用此结果创建一个新表。

SELECT
    CONCAT('CREATE TABLE ', QUOTE(new_table_name), ' AS ',
            GROUP_CONCAT(qry SEPARATOR ' UNION ALL '))
    INTO @sql
FROM (
    SELECT
        CONCAT('SELECT `acct`,', QUOTE(COLUMN_NAME), ' AS `Business_Unit`,`', COLUMN_NAME, '` AS `value` FROM `', @target_table, '` WHERE ', @target_where) qry
    FROM (
        SELECT `COLUMN_NAME` 
        FROM `INFORMATION_SCHEMA`.`COLUMNS` 
        WHERE `TABLE_SCHEMA`=@target_schema 
            AND `TABLE_NAME`=@target_table
            AND `COLUMN_NAME` != 'acct'
    ) AS `A`
) AS `B` ;

相关问题