2014-09-19 49 views
1

我在計算基於價格和獎品類別的收入方面存在問題。這是一個電影的價格表:SQL:基於價格類別的總價格

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 
....... 

,我怎麼計算蝙蝠俠的未來收益在2014-12- 01,帶有SQL查詢?

漢克

+0

爲什麼對上帝的愛沒有你把'在不同的領域Date'和'Time'。這使得這個問題變得如此令人難以置信。 SQL支持'datetime'字段是有原因的。 – 2014-09-19 10:40:11

回答

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'; 

關於數據結構的評論。你的表應該有主鍵,通常是自動遞增的整數,而不是使用字符串進行組合。就像你所做的那樣,分隔日期和時間沒有問題,特別是對於像「時間」代表每天插槽中的電影那樣的問題。

+0

+1理想情況下,價格應該有2欄,電影和價格類別 – 2014-09-19 10:46:41

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