我在根据价格和奖品类别计算收入方面存在问题。这是电影院价格表:
Prices
Movie Regular Student
Batman 8.50 7.50
Spiderman 6.50 6.00
The Godfather 5.50 4.50
.......
这是预订客户的表格:
Customers
Name Movie Date Price
Dennis Jones Batman 2014-12-01 Student
Al McGregor Spiderman 2014-12-01 Regular
Lee Wong Batman 2014-12-01 Regular
.......
基于此,如何使用SQL查询计算2014-12-01蝙蝠侠的未来收入?
汉克
答案 0 :(得分:2)
这基本上是带有条件聚合的join
:
select sum(case when price = 'Student' then Student
when price = 'Regular' then Regular
end)
from customers c join
prices p
on c.movie = p.movie
where date = '2014-12-01' and time = '1200' and Movie = 'Batman';
关于数据结构的评论。您的表应该有主键,通常是自动递增的整数,而不是使用字符串组合。正如您所做的那样,将日期和时间分开是没有问题的,尤其是对于像“时间”代表每天插槽的电影一样。
答案 1 :(得分:1)
我可能会选择以下内容:
Select Movie, MovieDate, MovieTime, Sum(PriceToPay)
from
(Select P.Movie, P.Regular, P.Student, C.Name, C.Date as MovieDate, C.Time as MovieTime, (Case when C.Price = 'Student' then P.Student else P.Regular end) as PriceToPay
from Prices P inner join Customer C on P.Movie = C.Movie) xxx
Group by Movie, MovieDate, MovieTime