动态 SQL 将许多列转换为行

问题描述 投票:0回答:1

我有一个包含 100 多列的表,我想保留 2 列作为固定列并转换其余列。我可以通过 union 来做到这一点,但这将是大量的工作和很长的代码。我想要更短的 SQL 代码来达到相同的结果。

SELECT 
material, plant, 'name' AS column_name, name AS column_value FROM materialtable 
UNION ALL 
SELECT 
material, plant, 'category' AS column_name, category AS column_value FROM materialtable 
UNION ALL 
SELECT material, plant, 'rating' AS column_name, CAST(rating AS STRING) AS column_value FROM materialtable UNION ALL 
SELECT 
material, plant, 'price' AS column_name, CAST(price AS STRING) AS column_value FROM materialtable

谢谢

我尝试了下面的代码,但有语法错误“语法错误:未闭合的字符串文字位于”。 我正在研究大查询平台。

DECLARE query STRING;

SET query = (
  SELECT CONCAT(
    'SELECT * FROM (',
    STRING_AGG(
      FORMAT(
        'SELECT 
           material,
           plant,
           "%s" AS column_name,
           CAST(%s AS STRING) AS column_value
         FROM materialtable',
        column_name,
        column_name
      ),
      ' UNION ALL '
    ),
    ')'
  )
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE table_name = 'materialtable'
    AND column_name NOT IN ('material', 'plant')
  ORDER BY ordinal_position
)

EXECUTE IMMEDIATE query;
                              
sql google-bigquery
1个回答
0
投票

发生这种情况是因为静态列列表之间的换行符:

试试这个方法:


BEGIN


DECLARE query STRING;
SET query = (
  SELECT CONCAT(
    'SELECT * FROM (',
    STRING_AGG(      FORMAT( 'SELECT    material,  plant, "%s" AS column_name, CAST(%s AS STRING) AS column_value   FROM materialtable',
        column_name,        column_name      ),      ' UNION ALL '    ),    ')'  )  FROM `region-us`.INFORMATION_SCHEMA.COLUMNS
  WHERE table_name = 'materialtable'AND column_name NOT IN ('material', 'plant')
  
);

EXECUTE IMMEDIATE query;  

END;
© www.soinside.com 2019 - 2024. All rights reserved.