TextJoin like function based on a condition in on SQL

纵然是瞬间 提交于 2021-01-05 08:59:46

问题


Trying to figure out if it is possible to do a textjoin like function in SQL based on a condition. Right now the only way I can think of doing it is by running a pivot to make the rows of the column and aggregating them that way. I think this is the only way to transpose the data in SQL?

Input This would be a aql table (tbl_fruit) that exists as the image depicts

SELECT * FROM tbl_fruit

Output


回答1:


Below is for BigQuery Standard SQL (without specifically listing each column, thus in a way that it scales ...)

#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`    

If to apply to sample data from your question - output is




回答2:


In Big Query, you could do this with arrays:

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

This puts all the columns in an array, transcoding each 1 to the corresponding literal string and 0s to null values. Then array_to_string() builds the output CSV string - this functions ignores null values by default.



来源:https://stackoverflow.com/questions/65345650/textjoin-like-function-based-on-a-condition-in-on-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!