如何select得到总值最高的对象组

How to select the the group of objects with the highest total value

我有三个这样的 table:

对象(NumId 是主键

NumId Object_category Price
1 permanent 20
2 borrowed 30
3 borrowed 10

集合(列名是主键

ColName
collection_alpha
collection_betha

借来

(NumObj 是 Foreign Key/Primary Key 引用对象 table,而 Collection_name外键引用集合table)

NumObj Collection_name
1 collection_alpha
2 collection_betha
3 collection betha

我需要做的查询是:“哪些藏品(不包括永久藏品)的借物总成本最高?”

我目前的尝试(无效):

SELECT ColName FROM Colecao
WHERE (
   SELECT MAX((SUM(Price)) FROM Objects AS Num
   JOIN Borrowed ON NumObj = Objects.NumId
   JOIN Collection ON ColName = Collection_name
   WHERE Num > COUNT(NumId) FROM Objects 
   WHERE Object_category = "permanent"
);

它 returns 消息:“语法错误”

"Which collections [...] have the highest total cost of borrowed objects?"

select
    b.Collection_name,
    sum(o.price) Worth
from
    Objects o
    inner join Borrowed b on b.NumObj = o.NumId
where
    o.Object_category = 'borrowed'
group by
    b.Collection_name
order by
    sum(o.price) desc

为您提供所有 collections 的列表,按所借 objects 的总价值降序排列。您可以添加 limit 1 以显示列表的顶部项目。

但假设有两个 collections 恰好具有相同的总价值。他们两者都有“最高的借贷总成本objects”,所以两者都应该returned。上面带有 limit 1 的查询将省略其中之一。

在这种情况下,我们可以 rank collections 根据它们的价值,return 所有排名为 1 的行。

select
    *
from
    (
    select
        *,
        rank() over (order by Worth desc) rnk
    from
        (
        select
            b.Collection_name,
            sum(o.price) Worth
        from
            Objects o
            inner join Borrowed b on b.NumObj = o.NumId
        where
            o.Object_category = 'borrowed'
        group by
            b.Collection_name
        ) collections
    ) collections_ranked
where
    rnk = 1
order by
    Collection_name

或者,我们可以设置一个 CTE 并像这样表达同样的事情:

with
    collections as (
        select
            b.Collection_name,
            sum(o.price) Worth
        from
            Objects o
            inner join Borrowed b on b.NumObj = o.NumId
        where
            o.Object_category = 'borrowed'
        group by
            b.Collection_name
    )
select
    Collection_name,
    Worth
from
    collections
where
    Worth = (select max(worth) from collections)
order by
    Collection_name