Skip to content
Advertisement

How can I group data from multiple rows into the same row?

I have a query:

select * from dwtrat_edu_tempdb.test1 

That returns

tile_to_update elementary_school   high_school   university
2270210        583                 null          null
2270210        321                 10529         null
2270210        null                null          58151

I want to combine the rows and take one value from each column (doesn’t matter which, first, last, can be any) So one elementary school, one high school, one university.

It would look like:

tile_to_update elementary_school   high_school   university
2270210        583                 10529         58151

However, when I try to group by:

select * from dwtrat_edu_tempdb.test1 
group by tile_to_update

I’m getting only a value for one of the columns and not a combination of all

tile_to_update elementary_school   high_school   university
2270210        null                10529         null

Thanks in advance for help.

Advertisement

Answer

If you don’t care about any specific value then ANY_VALUE/MIN/MAX is an option:

select tile_to_update,
       ANY_VALUE(elementary_school),ANY_VALUE(high_school),ANY_VALUE(university) 
from dwtrat_edu_tempdb.test1 
group by tile_to_update
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement