[英]Oracle: MAX of SUM of Each Group
My scenario is to show the hotel room with the highest maintenance cost for each hotel branch by using subqueries.我的场景是使用子查询显示每个酒店分支机构维护成本最高的酒店房间。 I have three separate tables: branch
, room
, and maintenance
.我有三个单独的表: branch
、 room
和maintenance
。
Table branch
表branch
id NUMBER(3) PRIMARY KEY
location VARCHAR2(20)
Table room
桌room
id NUMBER(3) PRIMARY KEY
room_number CHAR(4)
branch_id NUMBER(3)
Table maintenance
表maintenance
id NUMBER(3) PRIMARY KEY
room_id NUMBER(3)
cost NUMBER(4)
With my desired output being in the format我想要的输出格式为
location | room_number | cost
-------------------------------
| |
| |
| |
I'm not sure how to select the max value per branch after adding the total costs of each room.在添加每个房间的总成本后,我不确定如何选择每个分支的最大值。 Please advise.请指教。
You can use window functions:您可以使用窗口函数:
select *
from (
select b.location, r.room_number, m.cost,
rank() over(partition by b.id order by m.cost desc) rn
from branch b
inner join room r on r.branch_id = b.id
inner join maintenance m on m.room_id = r.id
) t
where rn = 1
If a room might have several maintenances, then we need aggregation:如果一个房间可能有多次维护,那么我们需要聚合:
select *
from (
select b.location, r.room_number, sum(m.cost) as cost,
rank() over(partition by b.id order by sum(m.cost) desc) rn
from branch b
inner join room r on r.branch_id = b.id
inner join maintenance m on m.room_id = r.id
group by b.id, b.location, r.room_number
) t
where rn = 1
You can use ROW_NUMBER()
analytic function along with joining those tables您可以使用ROW_NUMBER()
分析函数以及加入这些表
SELECT location, room_number, cost
FROM (SELECT b.location,
r.room_number,
m.cost,
ROW_NUMBER() OVER(PARTITION BY r.branch_id ORDER BY m.cost DESC) AS rn
FROM branch b
JOIN room r
ON r.branch_id = b.id
JOIN maintenance m
ON m.room_id = r.id)
WHERE rn = 1
PS If ties(the equal values of costs) matter(should be included even if generation for extra rows of maximum cost values are not problem), then you can replace ROW_NUMBER()
with DENSE_RANK()
PS如果关系(成本的相等值)很重要(即使生成最大成本值的额外行没有问题也应该包括在内),那么您可以用DENSE_RANK()
替换ROW_NUMBER()
DENSE_RANK()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.