小编典典

酒店预订价格SQL问题

sql

嗨,在阅读了StackOverflow上的其他问题后,我一直在尝试建立自己的系统来检查房间价格。

当预订日期中的房价没有重叠时,我的查询工作正常并产生正确的天数,但是当重叠时,我在第二行结果中得到了额外的一天。

例如,某人到达2011-04-14并离开2011-04-16(2天)。15日的费率从66更改为70,因此他应该以66的费率有1天,以70的费率有1天。

我尝试过没有TIMEDATE-只是DATE,但是发生了同样的事情。

询问

    SELECT rates.rate_id, rate_start_date, rate_end_date, rate_price, 
(DATEDIFF( IF (rate_end_date > '2011-04-16 14:00:00' , '2011-04-16 14:00:00', rate_end_date),
IF ( rate_start_date < '2011-04-14 12:00:00' , '2011-04-14 12:00:00' , rate_start_date )) +1 ) 
AS days FROM rates 
WHERE rate_start_date <= '2011-04-16 14:00:00' AND rate_end_date > '2011-04-14 12:00:00' 
ORDER BY rate_price ASC

费率表

rate_id rate     rate_start_date        rate_end_date
1       70      2011-04-15 00:00:00   2011-05-31 23:59:59
2       80      2011-06-01 00:00:00   2011-06-30 23:59:59
3      100      2011-07-01 00:00:00   2011-08-31 23:59:59
4       80      2011-09-01 00:00:00   2011-09-30 23:59:59
5       70      2011-10-01 00:00:00   2011-10-31 23:59:59
6       45      2011-11-01 00:00:00   2011-12-31 23:59:59
0       66      2011-01-01 00:00:00   2011-04-14 23:59:59

结果

rate_id  rate_start_date         rate_end_date       rate    days
0       2011-01-01 00:00:00    2011-04-14 23:59:59  66  1
1       2011-04-15 00:00:00    2011-05-31 23:59:59  70  2 <----this should be 1 day

我非常感谢任何帮助或解释,为什么我的查询为我提供了第二行结果的额外时间。

谢谢


阅读 238

收藏
2021-04-07

共1个答案

小编典典

谢谢您的回答,马丁给您提供了2行,但是没有几天…埃米利奥(Emilio)的回答让我开始思考如何设置费率。我将费率表更改为日期格式,而不是日期时间,并使rate_end_date与下一个rate_start_date在同一天。

0   66  2011-01-01  2011-04-15
1   70  2011-04-15  2011-06-01
2   80  2011-06-01  2011-07-01
3   100 2011-07-01  2011-09-01
4   80  2011-09-01  2011-10-01
5   70  2011-10-01  2011-11-01
6   45  2011-11-01  2012-01-01

然后放下+1并

SELECT rates.rate_id, rate_start_date, rate_end_date, rate_price, 
(DATEDIFF( IF (rate_end_date > '2011-04-16' , '2011-04-16', rate_end_date), 
IF ( rate_start_date < '2011-04-14' , '2011-04-14' , rate_start_date )) ) 
AS days FROM rates WHERE rate_start_date <= '2011-04-16' 
AND rate_end_date > '2011-04-14' 
ORDER BY rate_price ASC

生产的

rate_id   rate_start_date   rate_end_date   rate  days    
    0   2011-01-01  2011-04-15  66  1
    1   2011-04-15  2011-06-01  70  1

以及从4月1日到8日没有重叠率的查询:

SELECT rates.rate_id, rate_start_date, rate_end_date, rate_price, 
(DATEDIFF( IF (rate_end_date > '2011-04-08' , '2011-04-08', rate_end_date), 
IF ( rate_start_date < '2011-04-01' , '2011-04-01' , rate_start_date )) ) 
AS days FROM rates WHERE rate_start_date <= '2011-04-08' 
AND rate_end_date > '2011-04-01' 
ORDER BY rate_price ASC

产生:

rate_id   rate_start_date    rate_end_date   rate  days
    0     2011-01-01       2011-04-15     66    7

感谢agiain的帮助!

2021-04-07