TextJoin 类函数基于 SQL 中的条件
TextJoin like function based on a condition in on SQL
尝试找出是否可以根据条件在 SQL 中执行类似 textjoin 的函数。现在我能想到的唯一方法是 运行 一个枢轴来制作列的行并以这种方式聚合它们。我认为这是转置 SQL?
中数据的唯一方法
输入 这将是一个 aql table (tbl_fruit),如图所示
SELECT *
来自 tbl_fruit
输出
在 Big Query 中,您可以使用数组执行此操作:
select grp,
array_to_string(
[
case when apples = 1 then 'apples' end,
case when oranges = 1 then 'oranges' end,
case when bananas = 1 then 'bananas' end,
case when grapes = 1 then 'grapes' end
],
','
) as output
from mytable
这会将所有列放入一个数组中,将每个 1
转码为相应的文字字符串,将 0
转码为 null
值。然后 array_to_string()
构建输出 CSV 字符串 - 此函数默认忽略 null
值。
以下适用于 BigQuery Standard SQL(没有具体列出每一列,因此以某种方式扩展...)
#standardSQL
select `Group`, string_agg(split(kv, ':')[offset(0)], ', ') output
from `project.dataset.table` t,
unnest(split(translate(to_json_string((select as struct t.* except(`Group`))), '{}"', ''))) kv
where split(kv, ':')[offset(1)] != '0'
group by `Group`
如果应用于您问题中的示例数据 - 输出为
尝试找出是否可以根据条件在 SQL 中执行类似 textjoin 的函数。现在我能想到的唯一方法是 运行 一个枢轴来制作列的行并以这种方式聚合它们。我认为这是转置 SQL?
中数据的唯一方法输入 这将是一个 aql table (tbl_fruit),如图所示
SELECT * 来自 tbl_fruit
输出
在 Big Query 中,您可以使用数组执行此操作:
select grp,
array_to_string(
[
case when apples = 1 then 'apples' end,
case when oranges = 1 then 'oranges' end,
case when bananas = 1 then 'bananas' end,
case when grapes = 1 then 'grapes' end
],
','
) as output
from mytable
这会将所有列放入一个数组中,将每个 1
转码为相应的文字字符串,将 0
转码为 null
值。然后 array_to_string()
构建输出 CSV 字符串 - 此函数默认忽略 null
值。
以下适用于 BigQuery Standard SQL(没有具体列出每一列,因此以某种方式扩展...)
#standardSQL
select `Group`, string_agg(split(kv, ':')[offset(0)], ', ') output
from `project.dataset.table` t,
unnest(split(translate(to_json_string((select as struct t.* except(`Group`))), '{}"', ''))) kv
where split(kv, ':')[offset(1)] != '0'
group by `Group`
如果应用于您问题中的示例数据 - 输出为