java max sum,使用max()和sum()

I need to find the 'name of the branch that has made the most money in 2009'. My tables are below:

Rental

(cid, copyid, outdate, returndate, cost)

Copy

(copyid, mid, bid)

Branch

(bid, bname, baddress)

I have written the following code, and it outputs the sum of all branches, but I need the sum of the branch that made the most money. I am not sure how to join a max() and sum() function in the same query. I am using Oracle 2007.

Output the branch name and sum (I get a summary of all branches with this):

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;

Output the max of sum (I don't get my branch name with this):

SELECT sum(total_cost)

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

How can I merge these two together to get only the max sum branch name?

解决方案

Why not just grab the top row from your first query?

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;

One thing you may be forgetting however, is that two branches could tie for making the most money. If you want to include all branches that participate in the tie for 1st place you might go with something like this (Oracle 9i or later).

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值