一个查询中有两个Oracle Sum函数

时间:2013-05-24 21:57:21

标签: sql oracle sum

这是我的问题。我有三个Oracle表。

表格构建:

Building_Id | Building_Description
----------------------------------
B1          | Building1

表室:

Building_Id | Room_ID | Room_Sqft | Floor_ID
--------------------------------------------
B1          | R1      | 555       | F1
B1          | R2      | 333       | F1
B1          | R3      | 666       | F2
B1          | R4      | 111       | F2

表:楼层

Building_Id | Floor_ID | Floor_Sqft
----------------------------------
B1          | F1       | 999
B1          | F2       | 888

我想要完成的是一组看起来像这样的总和:

Building_Id | Sum_of_Floors | Sum_of_Rooms
------------------------------------------
B1          | 1887          | 1665

由于地板上的房间总和不等于地板的总数,因此并不像将房间总和两次那样简单。有关如何构建查询以获得我需要的任何提示吗?

2 个答案:

答案 0 :(得分:0)

您应该能够编写一个查询,例如:

select
    building_id,
    sum_floors = (select sum(floor_sqft) from floor f where f.building_id = b.building_id),
    sum_rooms = (select sum(room_sqft) from room r where r.building_id = b.building_id
from building b

答案 1 :(得分:0)

SELECT Building_Id,
       (SELECT SUM(Floor_SqFt)
          FROM Floor f
         WHERE f.Building_ID = b.Building_Id) Sum_of_Floors,
       (SELECT SUM(Room_SqFt)
          FROM Rooms r
         WHERE r.Building_ID = b.Building_Id) Sum_of_Rooms
  FROM building b
相关问题