2010-10-12 100 views
0

我需要找到'2009年賺錢最多的分支的名稱'。我的表如下:使用max()和sum()

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

Copy 
(copyid, mid, bid) 

Branch 
(bid, bname, baddress) 

我已經寫了下面的代碼,它輸出所有分支的總和,但我需要最賺錢的分支的總和。我不知道如何在同一個查詢中加入max()和sum()函數。我使用的甲骨文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

爲什麼不直接從第一個查詢中獲取第一行?

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; 
+0

謝謝!我以前沒有用過rownum - 我對sql很新。我嘗試使用top 1,但Oracle似乎沒有認出它,除非我錯誤地使用它。 – user457666 2010-10-12 15:39:40

+0

TOP是MS SQL命令,我不認爲oracle支持它。 – JohnFx 2010-10-12 15:54:09

+2

'ROWNUM'將在'ORDER BY'之前被評估,所以你會得到一個結果,但不一定是你想要的結果。您需要在訂單後包裝查詢和用戶'ROWNUM',如@Jim Hudson的回答。 – 2010-10-12 15:55:10

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;