calculate price between given dates in multiple ranges

孤街浪徒 提交于 2019-12-08 04:37:24

问题


Hi the following code works well when used over two or more ranges but not when the start date and end date are in the same range. When the start date and end date are in the same range the totalprice returns an extra day. Hence the totalprice for one night is doubled.

Here is the mysql table;

CREATE TABLE rooms (
 Hotel_id INT,
 Room_id INT,
 Room_type VARCHAR(20),
 Start_date DATE,
 End_date DATE,
 Price INT
);

INSERT INTO rooms VALUES
(   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),
(   13   ,     3     ,    'luxury'  ,  '2012-10-01' ,  '2012-10-15'  , 15000);

Here is the code;

SELECT     SUM(
           CASE WHEN a.Start_date = b.min_sd AND a.Start_date <> b.max_sd THEN
                    (DATEDIFF(a.End_date, '2012-09-03')+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-09-03')+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-09-03' AND
              Start_date <= '2012-09-04'
       ) b
WHERE      a.Room_type   = 'luxury'     AND
       a.End_date   >= '2012-09-03' AND
       a.Start_date <= '2012-09-04';

回答1:


You could use a query like this:

SELECT
  SUM(
    DateDiff(
      Least(End_Date + INTERVAL 1 DAY, '2012-09-04'),
      Greatest(Start_Date, '2012-08-31')
    ) * Price
  )
FROM
  rooms a
WHERE
  a.Room_type   = 'luxury'     AND
  a.End_date   >= '2012-08-31' AND
  a.Start_date <  '2012-09-04';

Please see fiddle here.



来源:https://stackoverflow.com/questions/16306404/calculate-price-between-given-dates-in-multiple-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!