使用 max() 和 sum()
我需要找到“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;
如何将这两个合并在一起只获取最大总和分支名称?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有很多方法。例如,保留原始查询,您可以按总和对数据进行排序,然后只取第一行:
Lots of ways. For example, preserving your original query, you can order the data by the sum and then just take the first row:
为什么不直接从第一个查询中获取顶行呢?
然而,您可能忘记的一件事是,两个分支机构可能并列赚最多的钱。如果您想包括参与第一名并列的所有分支,您可以使用类似的东西(Oracle 9i 或更高版本)。
Why not just grab the top row from your first query?
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).