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 美元,因此只需计算创建唯一租金编号的次数并将其乘以固定费用,这是一个简单的计算。

我现在需要将其分解,并为每个流派或类别分配最高收入者。我完全被难住了......任何帮助将不胜感激。谢谢。

4

1 回答 1

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 语句来解决没有视图的问题。

于 2012-11-20T23:58:58.647 回答