问题
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 0
s 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