以下是我的表A
Column_Name Flag
----------- ----
col-A 1
col-B 1
col-C 1
col-D 2
列B中的col-A,col-B,col-C,col-D列如下
ID col-A col-B col-C col-D
1 a b c d
我想写一个类似的查询
select (select column_name from table-A where flag = 1) from table-B
以上查询应翻译为类似的内容
select col-A, col-B, col-C from table-B.
我尝试了以下操作:
select Array_to_String(Array(select column_name from table-A where flag = 1)) from table-B
但是上面的Array_to_string函数将列列表作为单个字符串提供给我。
答案 0 :(得分:1)
以下是BigQuery标准SQL的示例
我添加了另一个表(tableC),以便在group)flag和相应动作之间建立关联。总体而言,它得到了简化(根据您的问题),但是显示了可能的方法-您仍然需要将其应用于特定的用例
请注意,根据您的评论-我假设您对行中的列应用汇总
#standardSQL
WITH `tableA` AS (
SELECT 'colA' Column_Name, 1 Flag UNION ALL
SELECT 'colB', 1 UNION ALL
SELECT 'colC', 1 UNION ALL
SELECT 'colD', 2 UNION ALL
SELECT 'colE', 2
), `tableB` AS (
SELECT 1 id, 1 colA, 2 colB, 3 colC, 4 colD, 5 colE UNION ALL
SELECT 2, 5, 6, 7, 8, 9
), `tableC` AS (
SELECT 1 flag, 'SUM' action UNION ALL
SELECT 2, 'BIT_AND'
)
SELECT id,
CASE action
WHEN 'SUM' THEN SUM(CAST(val AS INT64))
WHEN 'BIT_AND' THEN BIT_AND(CAST(val AS INT64))
END val
FROM (
SELECT id,
SPLIT(kv, ':')[OFFSET(0)] col,
SPLIT(kv, ':')[OFFSET(1)] val
FROM `tableB` t,
UNNEST(SPLIT(REGEXP_REPLACE(TO_JSON_STRING(t), r'^{|}$|"', ''))) kv
)
JOIN `tableA` ON col = Column_Name AND flag = 1 -- set flag here
JOIN `tableC` USING(flag)
GROUP BY id, action
您只需要设置标志的值
如果将flag设置为1-结果将为列的总和
Row id val
1 1 6
2 2 18
如果将flag设置为2-结果将被BIT_AND应用于“幸存”列
Row id val
1 1 4
2 2 8