2012-11-20 58 views
1

基本上我正在做一個電影租賃公司數據庫。 我需要能夠提供比其他類別的電影賺錢更多的電影名稱。使用兩個單獨的表按類別查找最大值

目前,我有一個產品表和租賃表。

Product – 
Attributes: (Product_ID, Product_Title, Rating, Release_Date, Genre, Length_of_Movie, Director_Name, Key_Actor, Num_Copies) 
PK – Product_ID 

Rental – 
Attributes: (Rental_ID, Member_ID, Product_ID, Date_Rented, Date_Returned) 
PK – Rental_ID 
FK – Member_ID, Product ID 

每個租金都有$ 1.00的價值。我能夠獲得所有租金的收入,但我很難按照流派或類別獲得收入。我得到的收入作爲一個整體此查詢:

Select sum(count(Rental_ID) *1) as Revenue 
from Rental 
Group by Rental_ID;  

* *每租金爲$ 1.00美元所以這是一個簡單的計算,只是算一個獨特的租賃數量多少次創建和平板乘以費用。

我現在需要打破這種情況,並給每個類型或類別的最高收入者。我完全難住...任何幫助,將不勝感激。謝謝。

回答

0

我還沒有測試這一點,但:

我想創建一個視圖,讓每產品收入,像這樣

Create View RevenuePerProduct As 
Select 
    r.Product_ID, 
    Count(*) As Revenue -- as $1/rental we can just count 
From 
    Rental r 
Group By 
    r.Product_ID 

要獲取流派的最大收益,你可以利用視圖,我會做另一個叫做MaxRevenueByGenre的視圖。

Create View MaxRevenueByGenre As 
Select 
    p.Genre, 
    Max(rpp.Revenue) As MaxByGenre 
From 
    RevenuePerProduct rpp 
    Inner Join 
    Product p 
    On rpp.Product_ID = p.Product_ID 
Group By 
    p.Genre 

要獲得每種類型收入最高的產品(或多個產品)有點棘手,因爲您需要兩次參考收入部分。你會注意到兩個視圖都被使用。

Select 
    best.Genre, 
    best.ProductTitle, 
    rpp.Revenue 
From 
    Product best 
    Inner Join 
    RevenuePerProduct rpp 
    On best.Product_ID = rpp.Product_ID 
    Inner Join 
    MaxRevenueByGenre mpg 
    On best.Genre = mpg.Genre And rpp.Revenue = mpg.MaxByGenre 

如果他們與最高收入者並列,這將爲每個流派產生多個結果。

如果您願意,您可以通過在括號內替換視圖的select語句來獲得無視圖。

+0

非常感謝。這是一種嚴肅的生活救星......讓我走上正軌。我正試圖將我的頭圍繞幾個小時。再次感謝。 – user1840374