BigQuery 标准 SQL 如何将行转换为列

Posted

技术标签:

【中文标题】BigQuery 标准 SQL 如何将行转换为列【英文标题】:BigQuery Standrad SQL How to transpose a row into a column 【发布时间】:2016-07-27 08:47:50 【问题描述】:

我正在尝试在 BigQuery 中使用新的标准 SQL 功能。但是,我碰巧在文档中找不到有关如何执行以下操作的参考:

我的输入是:

我正在尝试将其转换为以下内容:

我希望像在 SQL 中一样使用 PIVOT 函数,但我找不到在 BigQuery 标准 SQL 功能中创建 PIVOT 的工作原理。

任何想法如何实现这一目标?

【问题讨论】:

【参考方案1】:

这不是 Pivoting,它是 UNION(逗号操作)

使用简单的联合

select B\B1 as B, 't1' as B, t1 as value,
select B\B1 as B, 'm1' as B, m1 as value,
select B\B1 as B, 'p1' as B, p1 as value;

【讨论】:

这行得通,但是我提供的表格是我必须为其执行此操作的表格的简化版本。我有数百个 B\B1s 值,我需要避免手动工作。 数据库中没有语法可以为您编写 SQL 代码。您将需要使用编码语言来为这种情况生成 SQL 语法。 我担心我将不得不诉诸于此。感谢您的帮助! 我收到了Syntax error: Expected keyword FROM but got keyword SELECT at [line]【参考方案2】:

请看下面的选项

您在 YourTable 中的行数在这里并不重要 - 但列数可以!

您需要在临时命名子查询下维护 ARRAY 创建,方法是将 SELECT 与必须转置的列一样多。在下面的示例中,您的问题中有三个。

对于这部分,没有办法avoid the manual work,而是通过在您选择的客户端中编码 - 通过使用tables.get API 加载表架构并循环通过schema's fields,同时构建下面的查询,然后最终运行它。 再次 - 这需要客户端编码,这看起来不像您在此处寻找的内容

那么,我们开始吧:

WITH temp AS (
  SELECT B, 
    ARRAY(
      SELECT AS STRUCT 't1' AS B1, t1 AS Value UNION ALL 
      SELECT AS STRUCT 'm1' AS B1, m1 AS Value UNION ALL 
      SELECT AS STRUCT 'p1' AS B1, p1 AS Value
    ) AS bb  
  FROM YourTable 
)
SELECT B, bb.B1 AS B1, bb.Value AS Value 
FROM temp t, t.bb  

你可以用

测试一下
WITH YourTable AS (
  SELECT 'a' AS B,  1 AS t1,  2 AS m1,  3 AS p1 UNION ALL
  SELECT 'b' AS B,  4 AS t1,  5 AS m1,  6 AS p1 UNION ALL
  SELECT 'c' AS B,  7 AS t1,  8 AS m1,  9 AS p1 UNION ALL
  SELECT 'd' AS B, 10 AS t1, 11 AS m1, 12 AS p1 UNION ALL
  SELECT 'e' AS B, 13 AS t1, 14 AS m1, 15 AS p1 UNION ALL
  SELECT 'f' AS B, 16 AS t1, 17 AS m1, 18 AS p1 
),
temp AS (
  SELECT B, 
    ARRAY(
      SELECT AS STRUCT 't1' AS B1, t1 AS Value UNION ALL 
      SELECT AS STRUCT 'm1' AS B1, m1 AS Value UNION ALL 
      SELECT AS STRUCT 'p1' AS B1, p1 AS Value
    ) AS bb
  FROM YourTable 
)
SELECT B, bb.B1 AS B1, bb.Value AS Value 
FROM temp t, t.bb 

【讨论】:

以上是关于BigQuery 标准 SQL 如何将行转换为列的主要内容,如果未能解决你的问题,请参考以下文章

SQL将行转置为列(按键变量分组)?

MS Access SQL 将行转换为列

将行转换为列

如何根据日期列将行转换为列?

SQL:将行转换为列

Oracle SQL Developer:如何使用 PIVOT 函数将行转置为列