Skip to content
Advertisement

GROUP CONCAT and LEFT OUTER JOIN to split

I’m working with SQL Workbench. This is an example of the tables I have:

I have not created this DB and can’t modify it. Each building corresponds to a site, so it contains a KEY to such site. Same with levels and buildings.

I am trying to get this result

the first two columns are easy, but I’m having issues with the 3rd. The parenthesis are illustrative, I don’t necessarily need those. But I need a way to split the string into levels by building_id.

Each (…) corresponds to the levels in one building.

This is the query I have working now which returns the first and second column. I have tried adding another LEFT OUTER JOIN to the query, but didn’t work. I tried many things but most of the things I try return errors or weird outputs.

Any help is appreciated. Thanks

Advertisement

Answer

You need two levels of aggregation: one by building_id and another by site_id.

id | buildings | levels                 
-: | :-------- | :----------------------
 1 | 1,2,3     | (1,2),(3,4,5),(6)      
 2 | 4,5,6     | (7,8),(9),(10,11)      
 3 | 7,8,9     | (12,13,14),(15,16),(17)
 4 | 10        | null                   

Or the same with lateral join:

db<>fiddle here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement