示例:
汽车
Number_plate | Car_Type | Year |Price_day |Price_hours |
AA8866DG | Mitsubishi Lancer | 2008 | $400 | $60 |
BG7677HJ | Toyota Harrier | 2010 | $600 | $80 |
H76868GB | Honda Jazz | 2009 | $550 | $50 |
交易
NumberTransac | Number_plate | Discount| Unit | Duration| Members_Id |Total_Price |
1 | AA8866DG | 0 | Hours | 8 | A01 | 0 |
2 | AB5536HG | 0 | Days | 2 | A01 | 0 |
3 | BG7677HJ | 0 | Days | 3 | A03 | 0 |
我想在Transaction表中计算基于total_price的单位数。
IF Unit = Hours Then
Car.Price_hours * Transaction.Duration
Else If Unit = Days Then
Car.Price_day * Transaction.Duration
End If
我对如何将该语句翻译成SQL语句感到困惑。
答案 0 :(得分:0)
如果您只想计算交易表中的所有总数,请执行此操作;
SELECT SUM(t.Total_Price) AS 'Total'
FROM Transaction AS t
如果您想从汽车表中获取价格,请执行此操作
SELECT CASE Unit
WHEN 'Hours' THEN t.duration * c.price_hours
WHEN 'Days' THEN t.duration * c.price_days
END AS 'Total Cost'
FROM Transaction AS t INNER JOIN
Cars AS c ON t.Number_plate = c.NumberPlate
答案 1 :(得分:0)
检查
SELECT Number_plate,CASE WHEN Unit='Hours' THEN Car.Price_hours * Transaction.Duration ELSE Car.Price_day * Transaction.Duration END AS Total_Price
FROM Car
INNER JOIN Transaction ON Car.Number_plate=Transaction.Number_plate