MySQL酒店客房价格查询

时间:2017-08-19 10:50:25

标签: mysql sql

我设计了一个小型酒店预订应用程序,我在酒店房间价格查询方面遇到了麻烦。

所以我想要的是这样的:

normal_price_table

room_id  | price
1          100
2          120

season_price_table

room_id | date      | price
1         2017-08-01    125
1         2017-08-02    125
2         2017-08-01    150 
2         2017-08-02    150 

我正在寻找具有此结果的SQL查询:

查询1:2017-08-01至2017-08-04之间的房价 这是2天的正常价格+ 2天的季节价格

room_id |  price
1          450 ( 200 normal price + 2* 125 season price)
2          540 ( 240 normal price + 2* 150 season price)

查询2:2017-08-06至2017-08-09之间的房价 这是4天的正常价格

room_id |  price
1          400 ( 4 * 100 normal price )
2          480 ( 4 * 120 normal price )

任何有关如何实现此查询的指南和帮助表示赞赏! 谢谢!

2 个答案:

答案 0 :(得分:1)

您需要添加季节价格和正常价格之和乘以正常天数。正常天数是DATEDIFF + 1减去季节天数。

select 
  n.room_id,
  coalesce(sum(s.price), 0) + n.price * (datediff(@to_date, @from_date) - count(s.price) + 1) as price
from normal_price_table n
left join season_price_table s
  on  s.room_id = n.room_id
  and s.date between @from_date and @to_date
group by n.room_id;

http://rextester.com/HBLRC69992

如果您的日历表包含应用程序生命周期中所需的所有日期,则可以简化SELECT逻辑:

select n.room_id, sum(coalesce(s.price, n.price)) as price
from normal_price_table n
join calendar c on c.date between @from_date and @to_date
left join season_price_table s
  on  s.room_id = n.room_id
  and s.date    = c.date
group by n.room_id;

http://rextester.com/ZDR40157

答案 1 :(得分:0)

以下是对它的查询

查询1:2017-08-01至2017-08-04之间的房价这是2天的正常价格+ 2天的季节价格

SELECT X.room_id, SUM(X.price) as price
FROM
(
    SELECT
      np.room_id,
      (SUM(np.price) * ( SELECT COUNT(0) FROM season_price_table spt1 WHERE 
                         spt1.date >= '2017-08-01'
                         AND spt1.date <= '2017-08-04'
                         AND spt1.room_id = np.room_id)) as price
      FROM normal_price_table np GROUP BY np.room_id
    UNION
    SELECT spt.room_id, SUM(spt.price) as price
    FROM season_price_table spt
    WHERE spt.date >= '2017-08-01' and spt.date <= '2017-08-04'
    GROUP BY spt.room_id
) X GROUP BY X.room_id

查询2:2017-08-06至2017-08-10之间取得房价这是4天正常价格

SELECT np.room_id,
       (SUM(np.price) * ( SELECT COUNT(0) FROM season_price_table spt1 
                           WHERE spt1.date >= '2017-08-06'
                           AND spt1.date <= '2017-08-10' 
                           AND spt1.room_id = np.room_id)) as price
FROM normal_price_table np GROUP BY np.room_id