我有要排除的年份、月份和日期的表格,如下所示
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
(作为日期列表或范围)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句