如何在 bigquery 中仅动态反转那些具有特定后缀的列

how to dynamically unpivot only those columns with a specific suffix in bigquery

我有一个table,有很多列(大约900列,这使得单独写所有列名是不可行的)。我怎样才能只动态地取消透视带有后缀“_next”和“_last”的列(有数百个这样的列)?例如:

TABLE:

+---------+------------+-----------+-------+----------+-----------+
|name     |product_next|upload_last|product|books     |active_next|
+---------+------------+-----------+-------+----------+-----------+
|    alice|       a    |   100     |apple  | 10       | 1         |
|      bob|       b    |    23     |orange | 2        | 0         | 
+---------+------------+-----------+-------+----------+-----------+

最终 TABLE(逆透视后):

+---------+------------+-----------+-------+----------+
|name     |metric      |value      |product|books     |
+---------+------------+-----------+-------+----------+
|    alice|product     |   a       |apple  | 10       | 
|      bob|product     |    b      |orange | 2        | 
|    alice|upload      |   100     |apple  | 10       | 
|      bob|upload      |    23     |orange | 2        | 
|    alice|active      |    1      |apple  | 10       | 
|      bob|active      |    0      |orange | 2        |
+---------+------------+-----------+-------+----------+

考虑以下方法

select * from your_table
unpivot (metric for col in (product_next, upload_last, active_next))    

如果应用于您问题中的样本数据

with your_table as (
  select 'alice' name, 'a' product_next, '100' upload_last, 'apple' product, '10' books, '1' active_next union all
  select 'bob', 'b', '23', 'orange', '2', '0'  
)    

输出是

此外,对于@Mikhail 正确的答案,您需要添加一个带有 REGEXP_CONTAINS 表达式的 WHERE 子句,如下所示:

where REGEXP_CONTAINS(col, '_next') OR REGEXP_CONTAINS(col,'_last')

完整的查询将是:

select * from your_table
unpivot (metric for col in (product_next, upload_last, active_next)) 
where REGEXP_CONTAINS(col, '_next') OR REGEXP_CONTAINS(col,'_last')