尝试弄清楚是否可以基于条件在 SQL 中执行类似文本连接的函数。现在我能想到的唯一方法是运行一个枢轴来制作列的行并以这种方式聚合它们。我认为这是在 SQL 中转置数据的唯一方法?
输入这将是一个aql表(tbl_fruit),如图所示存在
选择* 来自 tbl_fruit
输出
下面是 BigQuery 标准 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`
如果适用于您问题中的示例数据 - 输出为
在 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
值。
作为初学者,我以自己的方式尝试过。
with pt as (select Group_,
concat( 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)
opt from fruit)
select Group_,stuff(opt,len(opt),1,'') output from pt