如何从多个时间范围中进行选择

时间:2019-04-16 12:37:05

标签: sql-server

让我们说我在SQLServer中有一个名为Events的表。它包含一些带有时间戳的事件。

ID  TimeStamp             EventDescription
1   '2019-04-04 08:20'    Machine Error 1
2   '2019-04-04 09:01'    Machine Error 2
3   '2019-04-05 09:23'    Machine Error 3
4   '2019-04-05 12:23'    Machine Error 4
5   '2019-04-06 11:33'    Machine Error 5
6   '2019-04-06 18:07'    Machine Error 6
7   '2019-04-07 12:23'    Machine Error 7

此外,我还有第二个表,名为Ranges。它包含时间范围。

ID  From                  To
1   '2019-04-04 08:00'    '2019-04-04 09:00'
2   '2019-04-05 10:30'    '2019-04-05 16:00' 
3   '2019-04-06 10:00'    '2019-04-06 12:00'

我需要从表Event中选择事件,其中时间戳在表Ranges中的时间范围之间。

结果:

ID  TimeStamp             EventDescription
1   '2019-04-04 08:20'    Machine Error 1
4   '2019-04-05 12:23'    Machine Error 4
5   '2019-04-06 11:33'    Machine Error 5

我不知道该怎么办。 我必须使用动态SQL来构建此查询吗?

2 个答案:

答案 0 :(得分:2)

可以在此处使用相关子查询。

Select * from Events E
where exists (select 1 from Ranges where e.TimeStamp between [From] and [To])

答案 1 :(得分:2)

我将您的数据创建为临时表:

SELECT 1 ID,  CAST('2019-04-04 08:20' AS DATETIME) TimeStamp, 'Machine Error 1' EventDescription
INTO #Events
UNION
SELECT 2 ID,  CAST('2019-04-04 09:01' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription
UNION
SELECT 3 ID,  CAST('2019-04-05 09:23' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription
UNION
SELECT 4 ID,  CAST('2019-04-05 12:23' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription
UNION
SELECT 5 ID,  CAST('2019-04-06 11:33' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription
UNION
SELECT 6 ID,  CAST('2019-04-06 18:07' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription
UNION
SELECT 7 ID,  CAST('2019-04-07 12:34' AS DATETIME) TimeStamp, 'Machine Error 2' EventDescription


SELECT 1 ID, CAST('2019-04-04 08:00' AS DATETIME) [From], CAST('2019-04-04 09:00' AS DATETIME) [To]
INTO #Ranges
UNION
SELECT 2 ID, CAST('2019-04-05 10:30' AS DATETIME) [From], CAST('2019-04-05 16:00'  AS DATETIME) [To]
UNION
SELECT 3 ID, CAST('2019-04-06 10:00' AS DATETIME) [From], CAST('2019-04-06 12:00' AS DATETIME) [To]

然后就像将它们连接在一起一样简单:

SELECT E.*
FROM #Ranges R
JOIN #Events E ON E.TimeStamp BETWEEN R.[From] AND R.[To]