如何从列转置到行?

Posted

技术标签:

【中文标题】如何从列转置到行?【英文标题】:How to transpose from column to rows? 【发布时间】:2016-05-24 11:50:44 【问题描述】:

我有一张桌子:

a b c
<br> 1 2 3

a,b,c 是整数。 如何将行转置为两列:

<table style="width:100%">
  <tr>
    <td>col1</td>
    <td>col2</td> 
  
  </tr>
  <tr>
    <td>a</td>
    <td>1</td> 
    
  </tr>
   <tr>
    <td>b</td>
    <td>2</td> 
    
  </tr>
   <tr>
    <td>c</td>
    <td>3</td> 
    
  </tr>
</table>
(第一个表的列数没有设置) 谢谢,

【问题讨论】:

How to simulate a pivot table with BigQuery?的可能重复 【参考方案1】:

下面应该可以工作,但至少您需要提前知道 [first] 表中最大可能的列集 假设最大预期列数为 6 - 分别为:a、b、c、d、e、f

SELECT
  id,
  REGEXP_EXTRACT(pair, r'(\w+):') AS key,
  REGEXP_EXTRACT(pair, r':(\w+)') AS value
FROM (
  SELECT
    id, 
    SPLIT(CONCAT(
      'a:',IFNULL(STRING(a), ''), 
      ',b:', IFNULL(STRING(b), ''), 
      ',c:', IFNULL(STRING(c), ''), 
      ',d:', IFNULL(STRING(d), ''), 
      ',e:', IFNULL(STRING(e), ''), 
      ',f:', IFNULL(STRING(f), '')
    )) AS pair
  FROM (
    SELECT * FROM 
    YourTable,
    (SELECT NULL AS a, NULL AS b, NULL AS c, NULL AS d, NULL AS e, NULL AS f)
  )
)
HAVING NOT value IS NULL

试试下面的例子:

SELECT
  id,
  REGEXP_EXTRACT(pair, r'(\w+):') AS key,
  REGEXP_EXTRACT(pair, r':(\w+)') AS value
FROM (
  SELECT
    id, 
    SPLIT(CONCAT(
      'a:',IFNULL(STRING(a), ''), 
      ',b:', IFNULL(STRING(b), ''), 
      ',c:', IFNULL(STRING(c), ''), 
      ',d:', IFNULL(STRING(d), ''), 
      ',e:', IFNULL(STRING(e), ''), 
      ',f:', IFNULL(STRING(f), '')
    )) AS pair
  FROM (
    SELECT * FROM 
    (SELECT 1 AS id, 1 AS a, 2 AS b, 3 AS c),
    (SELECT 2 AS id, 4 AS a, 5 AS b, 6 AS c, 7 AS d),
    (SELECT 3 AS id, 8 AS a, 9 AS b, 10 AS c, 11 AS e),
    (SELECT NULL AS id, NULL AS a, NULL AS b, NULL AS c, NULL AS d, NULL AS e, NULL AS f)
  )
)
HAVING NOT value IS NULL

添加用于:我正在寻找没有联合或不知道最大预期列数的解决方案

使用客户端代码 - 你可以 a) 获取表的架构Tables: get API b) 像上面的答案一样构建动态 sql(现在没有联合) c) 执行sql

【讨论】:

感谢您的回答,但我正在寻找没有联合或不知道最大预期列数的解决方案。

以上是关于如何从列转置到行?的主要内容,如果未能解决你的问题,请参考以下文章

红移。我们如何(动态地)将表从列转置为行?

MySQL如何按列转置行

oracle sql 11G中如何将列转置为行

oracle如何在没有UNION的情况下将列转置为行

如何从包含集合的 pandas 列转置和转换为“one-hot-encode”样式?

将列转置为行 SQL Server