SQL : Select a dynamic number of rows as columns

前端 未结 4 1242
春和景丽
春和景丽 2021-01-22 23:21

I need to select static colums + a dynamic number of rows as columns in SQL

TABLE 1
-------
HotelID
BlockID
BlockName

TABLE 2
-------
BlockDate (unknown number          


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 00:07

    What you require is a pivot query, to convert row data into columnar:

      SELECT t.hotelid,
             t.blockid,
             t.blockname,
             MAX(CASE WHEN t2.blockdate = '02-10-10' THEN t.numberofrooms ELSE NULL END) AS 02_10_10,
             MAX(CASE WHEN t2.blockdate = '02-11-10' THEN t.numberofrooms ELSE NULL END) AS 02_11_10,
             MAX(CASE WHEN t2.blockdate = '02-12-10' THEN t.numberofrooms ELSE NULL END) AS 02_12_10,
             ...
        FROM TABLE_1 t
        JOIN TABLE_2 t2
    GROUP BY t.hotelid, t.blockid, t.blockname
    
    1. Mind that there's nothing to link the tables - realistically TABLE_2 needs hotelid and blockid attributes. As-is, this will return the results of TABLE_2 for every record in TABLE_1...

    2. The database is important, because it will need dynamic SQL to create the MAX(CASE... statements

提交回复
热议问题