需要帮助。
我有三个桌子
Building_master
-列:BuildingCode,建筑物名称
Floor_master
-列:FloorCode,Floor名称,BuildingCode
Room_Master
-列:RoomCode,RoomName,RoomFloor,RoomBulding
当我从Building Name
表中选择Building_master
时,我想填充GridView,输出将如下所示
Building Name: A
Floor
1 Room 101 Room 102 Room 103 Room 104
2 Room 201 Room 202 Room 203
3 Room 301 Room 302 Room 303 Room 304
请帮助为所需的输出创建SQL查询
答案 0 :(得分:1)
要绕过固定的列数(即每层最大房间数),可以加入,然后使用窗口函数和条件聚合:
select
building_name,
floor_name,
max(case when rn = 1 then room_name end) room1,
max(case when rn = 2 then room_name end) room2,
max(case when rn = 3 then room_name end) room3
from (
select
b.building_code,
b.building_name,
f.floor_code,
f.floor_name,
r.room_name,
row_number() over(
partition by b.building_code, f.floor_code order by r.room_code
) rn
from building_master b
inner join floor_master f
on f.building_code = b.building_code
inner join room_master r
on r.room_floor = f.floor_code
and r.room_building = b.building_code
) t
group by b.building_code, b.building_name, f.floor_code, f.floor_name
我不得不对您的架构中的关系进行一些猜测,您可能需要检查一下。
您可以通过在外部max()
上添加更多select
表达式来逐层处理更多房间。