Hotel_id Room_id Room_type Start_date End_date Price ---------------------------------------------------------------- 13 2 standard 2012-08-01 2012-08-15 7000 13 2 standard 2012-08-16 2012-08-31 7500 13 2 standard 2012-09-01 2012-09-30 6000 13 3 luxury 2012-08-01 2012-08-15 9000 13 3 luxury 2012-08-16 2012-08-31 10000 13 3 luxury 2012-09-01 2012-09-30 9500
嗨,这是我桌子的结构和数据。
我需要为酒店预订创建一个mysql查询,该查询将匹配数据库用户输入的数据:
对于Ex:
如果用户根据这些日期选择带豪华房的酒店(2012-08-30至2012-09-04) 8月30日和31日的总费用为(10000 * 2)+ 9月1日,2日和3日(9500 * 3)(不包括第4个结账日) 这意味着总价将为20000 + 28500 = 48500
因此查询应根据Hotel_id,Room_id,Start_date,End_date和Price
过滤总价由于
答案 0 :(得分:3)
使用此解决方案:
SELECT SUM(
CASE WHEN a.Start_date = b.min_sd AND a.Start_date <> b.max_sd THEN
(DATEDIFF(a.End_date, '2012-08-30')+1) * a.Price
WHEN a.Start_date = b.max_sd AND a.Start_date <> b.min_sd THEN
DATEDIFF('2012-09-04', a.Start_date) * a.Price
WHEN (a.Start_date,a.Start_date) IN ((b.min_sd,b.max_sd)) THEN
(DATEDIFF('2012-09-04', '2012-08-30')+1) * a.Price
WHEN a.Start_date NOT IN (b.min_sd, b.max_sd) THEN
(DATEDIFF(a.End_date, a.Start_date)+1) * a.Price
END
) AS totalprice
FROM rooms a
CROSS JOIN (
SELECT MIN(Start_date) AS min_sd,
MAX(Start_date) AS max_sd
FROM rooms
WHERE Room_type = 'luxury' AND
End_date >= '2012-08-30' AND
Start_date <= '2012-09-04'
) b
WHERE a.Room_type = 'luxury' AND
a.End_date >= '2012-08-30' AND
a.Start_date <= '2012-09-04'
分别用输入的开始日期和结束日期替换2012-08-30
和2012-09-04
的出现。
这将考虑同一个月的开始和结束日期以及跨越多个月。
答案 1 :(得分:2)
你可以使用MySQL的BETWEEN ... AND ...
操作员找到所需预订的日期范围(记得从给定的结账中休息一天)
日期,就像你说的,没有夜间住宿),然后按房间分组结果并采取
SUM()
价格乘以夜数(可以
使用MySQL的LEAST()
和。来计算
GREATEST()
函数):
SELECT Room_id,
SUM(Price * (1 + DATEDIFF(
LEAST(End_date, '2012-09-04' - INTERVAL 1 DAY),
GREATEST(Start_date, '2012-08-30')
))) AS Total
FROM mytable
WHERE Room_type = 'luxury' AND (
'2012-09-04' - INTERVAL 1 DAY
BETWEEN Start_date AND End_date
OR '2012-08-30' BETWEEN Start_date AND End_date
)
GROUP BY Room_id
在sqlfidde上查看。
答案 2 :(得分:0)
试试这个:
set @Hotel_id :=13;
set @Room_id :=3;
set @Start_date :='2012-08-30' ;
set @End_date :='2012-09-04';
select sum(b.TotalPrice-b.deductions) as total_cost from
( select a.Price,a.StartDate,a.EndDate,price*(DATEDIFF(a.EndDate,a.StartDate)+1) as TotalPrice
,case when a.EndDate=@End_date then a.Price else 0 end as deductions
from
(select price,case when @Start_date>=Start_date then @Start_date else Start_date end as StartDate
,case when @End_date<=End_date then @End_date else End_date end as EndDate
from h_booking h1
where Hotel_id=@Hotel_id
and Room_id=@Room_id
and (@Start_date between Start_date and End_date or @End_date between Start_date and End_date ))a )b