查询结果作为嵌套查询中的列名

Query result as column name in nested query

问题:BigQuery 将行值解释为字符串而不是列名。

我有两个表:

table_1
| ColumnA  | ColumnB  | ColumnC  |
| 123      | 345      | ColumnD  |
| 678      | 900      | ColumnE  |


table_2
| ColumnD | ColumnE | ColumnF |
| nn      | xx      | 123     |
| kk      | yy      | 678     |

我现在要做的是根据 table_1.

中的行,将 table_2 中一列中的两个表和 select 值组合起来

像这样:

SELECT 
   (SELCT ColumnC FROM table_2 WHERE ColumnF = table_1.ColumnA ) 
FROM table_1

问题是 BigQuery 将 ColumnC 解释为字符串。因此,它不是从 ColumnD 和 ColumnE 获取值,而是输出 'ColumnC'

以下适用于 BigQuery 标准 SQL

Option 1 - you know column names in table_2 in advance and there are not so many of them so you can check them in the query one by one as below

#standardSQL
SELECT a.*,
  CASE 
    WHEN ColumnC = 'ColumnD' THEN ColumnD
    WHEN ColumnC = 'ColumnE' THEN ColumnE   
  END value
FROM `project.dataset.table_1` a
LEFT JOIN `project.dataset.table_2` b
ON ColumnF = ColumnA    

如果应用于您问题中的虚拟数据 - 它会给您以下结果

Row ColumnA ColumnB ColumnC value    
1   123     345     ColumnD nn   
2   678     900     ColumnE yy    

Option 2 - dynamic evaluation of columns, assuming that layout is simple as in your example in question, but allows to run query without worry of how many possible columns in table_2 and you don't even need to know their names (of course except columnF as it is JOIN key)

#standardSQL
SELECT a.*,
  (SELECT SPLIT(x,':')[OFFSET(1)]
    FROM UNNEST(SPLIT(REGEXP_REPLACE(TO_JSON_STRING(b), r'[{}"]', ''))) x
    WHERE SPLIT(x,':')[OFFSET(0)] = ColumnC
  ) value
FROM `project.dataset.table_1` a
LEFT JOIN `project.dataset.table_2` b
ON ColumnF = ColumnA   

此查询将 return 与选项 1

中的结果完全相同
Row ColumnA ColumnB ColumnC value    
1   123     345     ColumnD nn   
2   678     900     ColumnE yy