[英]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我正在尝试使用以下查询排除日期,但收到一条错误消息,指出 varchar 到 int 转换错误
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
:一种选择使用
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)
)
This assumes that sample_table(date)
stores an actual date
datatype (or the-like).这假设
sample_table(date)
存储实际date
数据类型(或类似的)。
If you are running SQL Server < 2016, where string_split()
is not available, an alternative uses string functions:如果您正在运行 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), ',%')
)
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).您应该有一个单独的表来存储每个
id
的排除日期(作为日期列表或范围)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.