簡體   English   中英

在sql查詢中排除日期范圍

[英]Excluding date range in sql query

我有要排除的年份、月份和日期的表格,如下所示

Year | Days                 | Month | Id
-----+----------------------+-------+----
2017 | 25,26,27,28,29,30,31 | 12    | 1
2018 | 1,2,3,4              | 1     | 2

我正在嘗試使用以下查詢排除日期,但收到一條錯誤消息,指出 varchar 到 int 轉換錯誤

Select * 
From Sample_Table st 
Inner Join Exclude_Table et On et.id = st.id 
Where st.day Not In (et.days) 

一種選擇使用string_split()並且not exists

select * 
from sample_table st 
where not exists (
    select 1
    from exclude_table et
    cross apply string_split(et.days, ',')
    where et.id = st.id and st.date = datefromparts(et.year, et.month, value)
)

這假設sample_table(date)存儲實際date數據類型(或類似的)。

如果您正在運行 SQL Server < 2016,其中string_split()不可用,則替代方法使用字符串函數:

select * 
from sample_table st 
where not exists (
    select 1
    from exclude_table et
    where 
        et.id = st.id 
        and et.year = year(st.date)
        and et.month = month(st.date)
        and concat(',', et.days, ',') like concat('%,', day(st.date), ',%')
)

請注意,這兩種解決方案基本上都是您損壞的設計的解決方法。 您應該有一個單獨的表來存儲每個id的排除日期(作為日期列表或范圍)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM