我有一个查询, 我有一个名为tblBooking的表 该表中有3列
Column Names BookingID StartTime EndTime
Datatype int DateTime DateTime
示例数据:
BookingID StartTime EndTime
1 10:00 11:00
2 11:00 12:00
3 01:30 03:30
我需要比较两列StartTime
EndTime
查询是:我必须alloacte资源,例如。会议室这可以每天进行
between 10:00 am to 7:00 pm.
所以我需要根据时间检查会议室的可用性。考虑所有场景。 这是我在接受采访时问到的一个问题,我无法回答,所以我需要找到如何做的方式
答案 0 :(得分:1)
看看这个例子。您需要检查重叠时段,因此选择具有没有结果的日期时间将是正确的。
|---| PERIOD
--------------------------------------
|---| FINE
|---| FINE
|------| NOT FINE
|---| NOT FINE
|-| NOT FINE
|------| NOT FINE
|---| FINE
|---| FINE
|-------------| NOT FINE
DECLARE @tblBookings TABLE(
BookingID INT,
StartTime DATETIME,
EndTime DATETIME
)
INSERT INTO @tblBookings SELECT 1, '01 Jan 2010 10:00:00', '01 Jan 2010 11:00:00'
INSERT INTO @tblBookings SELECT 2, '01 Jan 2010 11:00:00', '01 Jan 2010 12:00:00'
DECLARE @StartDate DATETIME,
@EndDate DATETIME
--Inside
SELECT @StartDate = '01 Jan 2010 10:30:00',
@EndDate = '01 Jan 2010 11:30:00'
SELECT *
FROM @tblBookings
WHERE NOT( @EndDate <= StartTime OR @StartDate >= EndTime)
--Overlapping left
SELECT @StartDate = '01 Jan 2010 09:30:00',
@EndDate = '01 Jan 2010 10:30:00'
SELECT *
FROM @tblBookings
WHERE NOT( @EndDate <= StartTime OR @StartDate >= EndTime)
--Overlapping right
SELECT @StartDate = '01 Jan 2010 11:30:00',
@EndDate = '01 Jan 2010 12:30:00'
SELECT *
FROM @tblBookings
WHERE NOT( @EndDate <= StartTime OR @StartDate >= EndTime)
--Overlapping left and right
SELECT @StartDate = '01 Jan 2010 09:30:00',
@EndDate = '01 Jan 2010 12:30:00'
SELECT *
FROM @tblBookings
WHERE NOT( @EndDate <= StartTime OR @StartDate >= EndTime)
--THIS ONE IS FINE
SELECT @StartDate = '01 Jan 2010 09:00:00',
@EndDate = '01 Jan 2010 10:00:00'
SELECT *
FROM @tblBookings
WHERE NOT( @EndDate <= StartTime OR @StartDate >= EndTime)
答案 1 :(得分:0)
你可以在where子句中有多个标准...
BETWEEN 可以比较多个日期和时间
例如:
where requestedStartTime not between startTime and endTime
and requestedEndTime not between startTime and endTime
答案 2 :(得分:0)
您可以使用以下查询找到指定日期/时间范围与表格中所有现有日期/时间范围之间的所有“冲突”:
DECLARE @YourTable table (BookingID int,StartTime datetime,EndTime datetime)
INSERT INTO @YourTable VALUES (1, '2010-03-03 10:00am', '2010-03-03 10:30am')
INSERT INTO @YourTable VALUES (2, '2010-03-03 11:30am', '2010-03-03 01:30pm')
DECLARE @StartDate datetime
,@EndDate datetime
SELECT @StartDate='2010-03-03 9:00am'
,@EndDate='2010-03-03 10:15am'
;WITH AllDates AS
(
SELECT @StartDate AS DateOf
UNION ALL
SELECT DATEADD(mi,30,DateOf) --smallest increment to consider is 30 minutes
FROM AllDates
WHERE DateOf<@EndDate
)
,Collisions AS
(SELECT
*
FROM @YourTable y
INNER JOIN AllDates a ON a.DateOf>=y.StartTime AND a.DateOf<=y.EndTime
)
SELECT * FROM Collisions
输出:
BookingID StartTime EndTime DateOf
--------- ----------------------- ----------------------- -----------------------
1 2010-03-03 10:00:00.000 2010-03-03 10:30:00.000 2010-03-03 10:00:00.000
1 2010-03-03 10:00:00.000 2010-03-03 10:30:00.000 2010-03-03 10:30:00.000
(2 row(s) affected)