Oracle: MAX of SUM of each Group

Posted

技术标签:

【中文标题】Oracle: MAX of SUM of each Group【英文标题】:Oracle: MAX of SUM of Each Group 【发布时间】:2021-03-04 14:40:12 【问题描述】:

我的方案是使用子查询显示每个酒店分店维护成本最高的酒店房间。我有三个单独的表:branchroommaintenance

branch

id             NUMBER(3) PRIMARY KEY
location       VARCHAR2(20)

room

id             NUMBER(3) PRIMARY KEY
room_number    CHAR(4)
branch_id      NUMBER(3)

maintenance

id             NUMBER(3) PRIMARY KEY
room_id        NUMBER(3)
cost           NUMBER(4)

我想要的输出格式为

location | room_number | cost
-------------------------------
         |             |
         |             |
         |             |

在添加每个房间的总成本后,我不确定如何选择每个分支的最大值。请指教。

【问题讨论】:

您是否尝试过编写查询? 【参考方案1】:

你可以使用窗口函数:

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

如果一个房间可能有多次维护,那么我们需要聚合:

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

【讨论】:

【参考方案2】:

您可以使用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

附注如果关系(成本的相等值)很重要(即使生成额外的最大成本值行没有问题,也应该包括在内),那么您可以将 ROW_NUMBER() 替换为 DENSE_RANK()

【讨论】:

这不会得到与最高成本绑定的行。

以上是关于Oracle: MAX of SUM of each Group的主要内容,如果未能解决你的问题,请参考以下文章

Max Sum of Max-K-sub-sequence(单调队列)

Max a Sum of a partition by

Leetcode: Max Sum of Rectangle No Larger Than K

[LeetCode] Max Sum of Rectangle No Larger Than K

Max Sum of Rectangle No Larger Than K

hdu 3415 Max Sum of Max-K-sub-sequence 单调队列优化DP