使用max()和sum()

时间:2010-10-12 15:23:44

标签: sql oracle aggregate

我需要找到“2009年赚钱最多的分支机构名称”。我的表格如下:

Rental
(cid, copyid, outdate, returndate, cost)

Copy
(copyid, mid, bid)

Branch
(bid, bname, baddress)

我编写了以下代码,它输出了所有分支的总和,但我需要最赚钱的分支的总和。我不知道如何在同一个查询中加入max()和sum()函数。我正在使用Oracle 2007。

输出分支名称和总和(我得到所有分支的摘要):

SELECT bname, sum(cost) as Total
FROM rented R join copy C on R.copyid = C.copyid join branch B on C.bid = B.bid
WHERE outdate between '20090101' and '20091231'
GROUP BY bname;

输出总和的最大值(我没有得到我的分支名称):

SELECT sum(total_cost)
FROM (SELECT max(cost) as total_cost FROM rented WHERE outdate between '20090101' and '20091231') x;

如何将这两者合并在一起才能获得最大总和分支名称?

2 个答案:

答案 0 :(得分:3)

很多方法。例如,保留原始查询,您可以按总和对数据进行排序,然后只取第一行:

select * from (
SELECT bname, sum(cost) as Total 
FROM rented R join copy C on R.copyid = C.copyid join branch B on C.bid = B.bid 
WHERE outdate between '20090101' and '20091231' 
GROUP BY bname
order by sum(cost) desc
)
where rownum = 1; 

答案 1 :(得分:2)

为什么不抓住第一个查询中的第一行?

   SELECT * FROM (
            SELECT bname, sum(cost) as Total
            FROM rented R join copy C on R.copyid = C.copyid join branch B on C.bid = B.bid
            WHERE outdate between '20090101' and '20091231' 
            GROUP BY bname
            ORDER BY sum(cost) desc) 
   WHERE ROWNUM=1;

然而,你可能会遗忘的一件事是,两个分支机构可以为赚到最多钱而打成平手。如果你想包括参加第一名并列的所有分支,你可能会使用这样的东西(Oracle 9i或更高版本)。

    SELECT * FROM (
           SELECT bname, 
           sum(cost) as Total, 
           RANK() OVER (ORDER BY sum(cost) desc) "Rank"
           FROM rented R 
           join copy C on R.copyid = C.copyid 
           join branch B on C.bid = B.bid
           WHERE outdate between '20090101' and '20091231'
          GROUP BY bname) 
     WHERE Rank=1;