I have two tables with a linking table describing their many-to-many relationship.
TABLE buildings
building_id
building_name
TABLE facility_types
facility_type_id
facility_type
TABLE buildings_2_facility_types
building_id
facility_type_id
Now I need a report including the facility types as columns per each building.
REPORT:
NAME golf pool garage
Building A Y N Y
Building B N Y Y
Building C N N N
How can I do this in SQL?
N.B. This will be part of a much larger query involving lots of other tables. I can do all that part, but converting rows to columns has got me vexed!
Converting rows to columns is a real pain and you have to understand that SQL is really not meant for this kind of operation.
It’s still possible, providing that the set of values to be transposed is small, known and limited. If not, you’ll have to rely on you application layer.
An exemple on how to do it should help you understand the 3 conditions:
Assuming a table
buildings_2_facility_types:You can get sthg out of it this way:
See ? small, known and limited :/
Of course, you can also do it with a proc stock but it’s usually not the prefered way.