如何计算每栋建筑的房间面积百分比?我有2张桌子:建筑物和房间。客房表中的每间客房均为面积,面积为平方米:
Rooms Table
Room Area Building FKey
Room1 10 BK
Room2 20 CK
Building Table
PKey Name
BK Building1
CK Building2
Result
Building area (%)
Building 1 10%
Building 2 30%
答案 0 :(得分:0)
我是否理解你想要每个房间的百分比到建筑物?或者您想看到每栋建筑的房间总数吗?
如果是后者,则需要绑定总建筑面积。
如果是前者,这样的事情应该有效...你基本上需要计算每个建筑物的总面积,然后将房间面积除以。
SELECT Building.Name,
Rooms.Name,
100.0 * Area / (SELECT SUM(R2.Area) FROM Rooms R2 WHERE R2.BuildingID = Rooms.BuildingID) AS Percentage
FROM Rooms
INNER JOIN Building
ON Rooms.BuildingID = Building.BuildingID
如果是后者,那么这样的事情(即使你没有指定存储总建筑面积的地方......假设在建筑物表上):
SELECT BuildingID, SUM(Rooms.Area) / Building.Area * 100.0
FROM Rooms
INNER JOIN Building
ON Rooms.BuildingID = Building.BuildingID
GROUP BY Building.BuildingID
答案 1 :(得分:0)
假设我终于明白了你想要计算的百分比(每个建筑物的总面积/所有建筑物的总面积),你可以尝试这样的事情:
SELECT Building.Name,
100.0 * Sum(Room.Area) / (SELECT SUM(R2.Area) FROM Rooms R2)
AS Percentage
FROM Rooms INNER JOIN Building
ON Rooms.BuildingID = Building.BuildingID
GROUP BY Building.Name