酒店预订季节总日期之间的价格

时间:2015-08-27 20:57:25

标签: sql sql-server

这是我的季节和价格表。

版本MsSql Server 2012

下面是表格结构 enter image description here

 user date input         
BeginDate : 2015-01-13     2 day  2*2 =4
EndDate   : 2015-01-18     3 day  3*2= 6
Total Price                          = 10   

日期范围之间的总价格(如酒店预订季节); 示例sql查询:

declare @DateStart date ='2015-01-13';declare @DateEnd date ='2015-01-18';
select *from Season s 
    inner join Price p on p.SeasonID=s.SeasonID
    WHERE (@DateStart BETWEEN s.BeginDate AND s.EndDate
       OR @DateEnd BETWEEN s.BeginDate AND s.EndDate
       or s.BeginDate BETWEEN @DateStart AND @DateEnd
       or s.EndDate BETWEEN @DateStart AND @DateEnd)
       and s.RoomID=1

如何使用我的日期范围计算总价?

1 个答案:

答案 0 :(得分:0)

您需要为我们提供更大的数据集和更多示例,以帮助您使此查询稳固。但问题的核心是计算每个SeasonID每次停留的天数。试试这个:

DECLARE @BeginDate  date = '2015-01-13'
DECLARE @EndDate    date = '2015-01-18'

;WITH
    tmp AS
    (
        SELECT  S.SeasonID,
                StayBeginDate = IIF(@BeginDate > S.BeginDate, @BeginDate, BeginDate),
                StayEndDate   = IIF(@EndDate   > S.EndDate,   S.EndDate,  @EndDate)
        FROM    Season  S
        WHERE   @BeginDate BETWEEN S.BeginDate AND S.EndDate
            OR  @EndDate   BETWEEN S.BeginDate AND S.EndDate
    )

SELECT      tmp.SeasonID, tmp.StayBeginDate, tmp.StayEndDate,
            DayCount = DATEDIFF(DAY, tmp.StayBeginDate, tmp.StayEndDate),
            Cost     = P.Price * DATEDIFF(DAY, tmp.StayBeginDate, tmp.StayEndDate)
FROM        tmp
INNER JOIN  Price   P   ON tmp.SeasonID = P.SeasonID

我相信你知道如何总计整个住宿的总费用。