如何检查日期是否不在多个范围内?

时间:2018-10-13 19:29:35

标签: sql sql-server tsql

我有一个名为“建筑物”的表格。该表列出了建筑物启用时的日期范围。建筑物的ID有时会重复。我想使用TSQL获取当天(20181013)尚未激活的所有不同建筑物,但我不知道如何。请你帮助我好吗? 理想情况下,我应该得到的是没有建筑物。 2和3。

建筑物:

+-------------+--------+-------------+-----------+
| Building_ID | LineID | Active_from | Active_to |
+-------------+--------+-------------+-----------+
|           1 |      1 |    20170101 |  20190101 |
|           2 |      1 |    20170203 |  20170903 |
|           2 |      2 |    20170904 |  20171231 |
|           2 |      3 |    20180101 |  20180910 |
|           2 |      4 |    20181101 |  20181231 |
|           3 |      1 |    20170101 |  20180631 |
|           3 |      2 |    20190101 |  20200101 |
|           4 |      1 |    20180101 |  20180631 |
|           4 |      2 |    20180701 |  20190101 |
+-------------+--------+-------------+-----------+

2 个答案:

答案 0 :(得分:0)

with
    cte
as
(
    select
        Building_ID
    from
        [Your_Table]
    where
        '20181013' between Active_from and Active_to
)
select
distinct
    Building_ID
from
    [Your_Table] yt
where
    Building_ID not in
    (
        select
            Building_ID
        from
            cte
    )

答案 1 :(得分:0)

它可以直接写成:

SELECT DISTINCT Building_ID
FROM Buildings b
WHERE NOT EXISTS (
  SELECT * FROM Buildings
  WHERE '20181013' BETWEEN Active_from AND Active_to
    AND Building_ID = b.Building_ID)