SQL 检查时间是否在一系列时间段内
SQL checking if time within a series of timebands
我想写 SQL 来检查 Table A 中的给定时间(例如 5:24 AM)是否在 [=24= 中的以下不规则时间段之一内] B.
5:00 AM to 6:00 AM
7:30 AM to 9:15 AM
1:26 PM to 2:45 PM
4:00 PM to 4:59 PM
10:00 PM to 11:14 PM
我的计划是写这个 SQL 语句:
CASE
WHEN [Given Time] BETWEEN [START TIME] and [END TIME] THEN 1
ELSE 0
END
但后来我意识到我需要编写 5 个连接——还有其他方法吗?
萨姆
请试试这个:
CASE
WHEN EXISTS (SELECT 1 FROM [My Time Table]
WHERE [Given Time] BETWEEN [START TIME] and [END TIME])
THEN 1
ELSE 0
END
我没有看到 CASE
声明或 JOIN
的单一原因。这应该足够了。
DECLARE @YourTime time = '05:42'
SELECT
*
FROM
YourTable
WHERE
@YourTime between [Start Time] and [End Time]
或者更明确地说...
...
WHERE
[Start Time] <= @YourTime
AND [End Time] >= @YourTime
我想写 SQL 来检查 Table A 中的给定时间(例如 5:24 AM)是否在 [=24= 中的以下不规则时间段之一内] B.
5:00 AM to 6:00 AM
7:30 AM to 9:15 AM
1:26 PM to 2:45 PM
4:00 PM to 4:59 PM
10:00 PM to 11:14 PM
我的计划是写这个 SQL 语句:
CASE
WHEN [Given Time] BETWEEN [START TIME] and [END TIME] THEN 1
ELSE 0
END
但后来我意识到我需要编写 5 个连接——还有其他方法吗?
萨姆
请试试这个:
CASE
WHEN EXISTS (SELECT 1 FROM [My Time Table]
WHERE [Given Time] BETWEEN [START TIME] and [END TIME])
THEN 1
ELSE 0
END
我没有看到 CASE
声明或 JOIN
的单一原因。这应该足够了。
DECLARE @YourTime time = '05:42'
SELECT
*
FROM
YourTable
WHERE
@YourTime between [Start Time] and [End Time]
或者更明确地说...
...
WHERE
[Start Time] <= @YourTime
AND [End Time] >= @YourTime