简体   繁体   中英

How to convert or transpose rows to columns in SQL without using pivot?

I have faced one issue while getting data transposed in SQL. for eg table given below

id source_name value
1 cp x
1 cp y
1 hi a
2 li b
2 cp c
2 li d
3 li e

I need this table in below format (transposed but with string aggregation)-

id cp hi li mi
1 x,y a null null
2 c null b,d null
3 null null null d

With the current sql query, I am getting table in below format.

id cp hi li mi
1 x a null null
2 c null b null
3 null null null d

Can anyone tweak the query or suggest new query in SQL (Platform - Bigquery)?

Current query -

select id, any_value(if(source_name = 'cp', value, null)) as cp,
any_value(if(source_name = 'hi', value, null)) as hi,
any_value(if(source_name = 'li', value, null)) as li
any_value(if(source_name = 'mi', value, null)) as mi
from table_name group by id

Try STRING_AGG instead of any_value :

select id, string_agg(if(source_name = 'cp', value, null)) as cp,
string_agg(if(source_name = 'hi', value, null)) as hi,
string_agg(if(source_name = 'li', value, null)) as li
string_agg(if(source_name = 'mi', value, null)) as mi
from table_name group by id

Use PIVOT operator instead

select *
from `project.dataset.table`
pivot (string_agg(value) for source_name in ('cp', 'hi', 'li', 'mi'))    

If applied to sample data in your question

在此处输入图片说明

output is

在此处输入图片说明

Check out https://stackoverflow.com/a/67479622/5221944 if you want to make it dynamically build list of columns for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM