我目前陷入任务7 http://sqlzoo.net/wiki/Guest_House_Assessment_Medium任务包括额外内容。计算预订总额5128,包括额外费用。
这就是我得到的
select sum(b.nights*r.amount+e.amount)
from booking b inner join rate r
ON room_type_requested=r.room_type
and
b.occupants=r.occupancy
inner join extra e on b.booking_id=e.booking_id
where b.booking_id=5128
回答我得到额外的是451.80,这显然是错误的。如果我只计算这些夜晚的房价金额
select sum(b.nights*r.amount)
from booking b inner join rate r
ON room_type_requested=r.room_type
and
b.occupants=r.occupancy
where b.booking_id=5128
我得到216.00这对于3晚没有额外费用的预订似乎是正确的。但是,在任务下建议的正确答案是118.56,附加内容。怎么会这样?
有人可以向我解释为什么它是118.56以及我做错了什么。 谢谢。
答案 0 :(得分:1)
你应该单独计算房间和额外账单的账单,然后将它们加在一起。
select bill_1 + bill_2
from
(select booking_id, sum(amount*nights) as bill_1 from
booking b JOIN rate r ON b.room_type_requested = r.room_type and b.occupants = r.occupancy
group by booking_id
having booking_id = 5128) t1
join
(select booking_id, sum(amount) as bill_2 from extra
group by booking_id
having booking_id = 5128) t2
on t2.booking_id = t1.booking_id;
答案 1 :(得分:1)
我刚刚经历过这些教程,这是我在SQLZOO上发现的一些不正确的答案之一,因此我在SO上找到了这篇文章,因为我试图弄清楚我在做什么错。
我认为值得强调的是,对于像这样的实例,如果您不同意网站的答案,您可以尝试解决问题,您可以输入更简单的查询来获取基础数据。在这种情况下,它确实表明网站的答案是错误的。
问:多少晚上的费率是多少?SELECT amount, nights
FROM booking JOIN rate ON
(room_type=room_type_requested AND occupancy=occupants)
WHERE booking_id=5128
Result = 3 nights at 72.00 = 216.00
问:有什么额外的东西?
SELECT * FROM extra WHERE booking_id=5128
Result is two items (breakfast and phone calls), 18.00 + 1.80 = 19.80
所以根据数据的正确答案是216.00 + 19.80 = 235.80。
答案 2 :(得分:0)
使用逻辑,SQL应为:
select sum(r2.amount * b1.nights)+ sum(e3.amount) as total
from booking b1
inner join rate r2
on r2.room_type = b1.room_type_requested
and r2.occupancy = b1.occupants
left join (select booking_id, sum(amount) as amount
from extra
group by booking_id) e3
on e3.booking_id = b1.booking_id
where b1.booking_id = 5128
返回235.80
答案 3 :(得分:0)
输出将为235.80
,但网站列出了错误的输出118.56
。
SELECT sum(b.nights * r.amount) +
(SELECT sum(e.amount)
FROM extra AS e
WHERE e.booking_id = b.booking_id)
FROM booking AS b
INNER JOIN rate AS r ON r.occupancy = b.occupants
AND r.room_type = b.room_type_requested
WHERE b.booking_id = 5128
GROUP BY b.booking_id;