根据当前日期选择一系列日期之间的行数

时间:2011-09-27 13:21:59

标签: sql-server

我正在做一个关于酒店预订的项目。我必须在页面中显示所选周的房间空缺。我正在从酒店预订表中预订房间数量。预订表中的预订数量很少。

enter image description here

我的问题是我必须在选定的一周内每个日期的hb_chkDt和hb_chkoDt之间得到HB_Noofrooms的总和。

离。假设如果我采用当前日期并检查它,那么我必须得到2作为总和。

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

如果您将日期作为您需要获得空缺的参数传递,那么这是一个简单的查询:

SELECT SUM(HB_NoOfRooms) FROM Booking 
WHERE HB_ChkDt <= @PassedDt AND HB_ChkODt >= @PassedDt 

但是如果你通过日期范围并希望在日期之间获得所有人的日期空缺,则需要进行一些复杂的查询。

更新:获取多个日期范围空缺的代码:

DECLARE @strSQL NVARCHAR(MAX)
DECLARE @StartDt DATETIME
DECLARE @EndDt DATETIME

CREATE TABLE #Booking (HB_Id INT, HB_ChkDt DATETIME, HB_ChkODt DATETIME, HB_NoOfRooms INT)

INSERT INTO #Booking VALUES (61, '2011-09-07 13:00:00','2011-09-08 13:00:00',1)
INSERT INTO #Booking VALUES (67, '2011-09-27 13:00:00','2011-09-28 2:00:00',1)
INSERT INTO #Booking VALUES (68, '2011-09-27 13:00:00','2011-09-28 2:00:00',1)
INSERT INTO #Booking VALUES (69, '2011-09-28 13:00:00','2011-09-29 2:00:00',1)

SET @StartDt = '2011-09-27'
SET @EndDt = '2011-09-29'

WHILE @StartDt <= @EndDt
BEGIN
    IF @strSQL IS NULL OR @strSQL = ''
        SET @strSQL = 'SELECT ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AS Dt, ISNULL(SUM(HB_NoOfRooms),0) AS Vacancy FROM #Booking WHERE CONVERT(VARCHAR(10),HB_ChkDt,102) <= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AND CONVERT(VARCHAR(10),HB_ChkODt,102) >= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''''
    ELSE
        SET @strSQL = @strSQL + ' UNION ALL SELECT ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AS Dt, ISNULL(SUM(HB_NoOfRooms),0) AS Vacancy FROM #Booking WHERE CONVERT(VARCHAR(10),HB_ChkDt,102) <= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AND CONVERT(VARCHAR(10),HB_ChkODt,102) >= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''''

    SET @StartDt = DATEADD(D,1,@StartDt)
END

EXEC (@strSQL)
DROP TABLE #Booking

答案 1 :(得分:1)

DECLARE @BeginDate date='2010-01-01'
DECLARE @EndDate date='2011-01-01'
; With Dates([Date]) as (
SELECT @BeginDate
UNION ALL
SELECT DATEADD(Day,1,Date) FROm  Dates 
WHERE Dates.date<@EndDate
)
SELECT Dates.Date,(SELECT COUNT(HB_No_Of_Rooms) FROM @MyTable WHERE HB_CkdDT>=Dates.date
AND HB_ChkODt<=Dates.Date
GROUP By HB_No_Of_Rooms
)
FROM Dates
OPTION(MAXRECURSION 0)

答案 2 :(得分:1)

如果您想要检索一周内占用的房间总数:

select sum(HB_NoOfRooms) from Booking 
where (hb_chkDt >= CONVERT(DATETIME, '2011-09-25 00:00:00') and  hb_chkDt < CONVERT(DATETIME, '2011-10-01 00:00:00')) 
or (HB_ChkODt >= CONVERT(DATETIME, '2011-09-25 00:00:00') and  HB_ChkODt < CONVERT(DATETIME, '2011-10-01 00:00:00')) 

如果您想查看今天占用的房间总数:

select sum(HB_NoOfRooms) FROM Booking          
where HB_ChkDt <=SYSDATETIME() AND HB_ChkODt >SYSDATETIME()