如何从列转换为行?

时间:2016-05-24 11:50:44

标签: google-bigquery

我有一张桌子:



a b c
<br> 1 2 3
&#13;
&#13;
&#13;

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;  (未设置第一个表中的列数) 感谢,

1 个答案:

答案 0 :(得分:0)

下面的

应该有效,但至少你需要提前知道[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