简体   繁体   中英

Excluding date range in sql query

I have table with year, month and dates to be excluded like shown below

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

I am trying to exclude dates using below query, but getting an error saying varchar to int conversion error

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

One option uses string_split() and 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)
)

This assumes that sample_table(date) stores an actual date datatype (or the-like).

If you are running SQL Server < 2016, where string_split() is not available, an alternative uses string functions:

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), ',%')
)

Note that both these solutions are basically workarounds for your broken design. You should have a separate table to store the exclusion dates of each id (either as a list of dates or as of ranges).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM