[英]Find values based on one column table from another table.Pivot
Help needed.需要帮助。
I have three tables我有三张桌子
Building_master
- columns: BuildingCode, Building Name Building_master
- 列:BuildingCode、Building Name
Floor_master
- columns: FloorCode, Floor Name, BuildingCode Floor_master
- 列:FloorCode、Floor Name、BuildingCode
Room_Master
- columns: RoomCode, RoomName, RoomFloor, RoomBulding Room_Master
- 列:RoomCode、RoomName、RoomFloor、RoomBulding
I want to fill the GridView when I select Building Name
from Building_master
table where the output will be something like below我想填写 GridView 当我 select Building Name
来自Building_master
表,其中 output 将如下所示
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
Kindly help to create a SQL query for the desired output请帮助为所需的 output 创建 SQL 查询
To pivot over a fixed number of columns (that is, the maximum number of rooms per floor), you can join, then use window functions and conditional aggregation:要将 pivot 超过固定的列数(即每层的最大房间数),可以加入,然后使用 window 函数和条件聚合:
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
I had to make a few guesses about the relationships in your schema, that you might need to review.我不得不对您的架构中的关系做出一些猜测,您可能需要查看这些猜测。
You can handle more rooms by floor by adding more max()
expressions to the outer select
.您可以通过向外部select
添加更多max()
表达式来按楼层处理更多房间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.