Tsql T-SQL检查一个表中的日期是否在另一个表中的两个日期之间,然后设置值
我有两张表,如下所示。我想根据下面的逻辑创建一个新变量(值),并在第三个表中显示结果?如何在T SQL中执行此操作 表1Tsql T-SQL检查一个表中的日期是否在另一个表中的两个日期之间,然后设置值,tsql,sql-server-2012,Tsql,Sql Server 2012,我有两张表,如下所示。我想根据下面的逻辑创建一个新变量(值),并在第三个表中显示结果?如何在T SQL中执行此操作 表1 ID, DATE ID, DATE1, DATE2 表2 ID, DATE ID, DATE1, DATE2 设置值的逻辑: FOR ALL TABLE_1.ID IF TABLE_1.DATE IS BETWEEN TABLE_2.DATE1 AND TABLE_2.DATE2 THEN VALUE = 1 EL
ID, DATE
ID, DATE1, DATE2
表2
ID, DATE
ID, DATE1, DATE2
设置值的逻辑
:
FOR ALL TABLE_1.ID
IF TABLE_1.DATE IS BETWEEN TABLE_2.DATE1 AND TABLE_2.DATE2
THEN VALUE = 1
ELSE VALUE = 0
IF TABLE_1.ID NOT IN TABLE_2
THEN VALUE = NULL
如果要查看
table_1.id=table_2.id
的所有行(以及table_1
中与id
不匹配的行)的结果,则可以使用左联接
和大小写
表达式:
select
t.id
, t.date
, IsBetween = case
when t.date between t2.Date1 and t2.Date2
then 1
when t2.id is null
then null
else 0
end
, t2.*
from table_1 as t
left join table_2 as t2
on t.id = t2.id
select
t.id
, t.date
, IsBetween = case
when t.date between x.Date1 and x.Date2
then 1
when x.id is null
then null
else 0
end
from table_1 t
outer apply (
select top 1 t2.*
from table_2 t2
order by case
when t.date between t2.Date1 and t2.Date2
then 0
else 1
end
) as x
如果您只想为表1
中的每一行指定一行,并且想知道表1.data
是否在表2
中的任何对应行之间,那么我们可以使用外部应用
来选择top 1
和大小写
表达式:
select
t.id
, t.date
, IsBetween = case
when t.date between t2.Date1 and t2.Date2
then 1
when t2.id is null
then null
else 0
end
, t2.*
from table_1 as t
left join table_2 as t2
on t.id = t2.id
select
t.id
, t.date
, IsBetween = case
when t.date between x.Date1 and x.Date2
then 1
when x.id is null
then null
else 0
end
from table_1 t
outer apply (
select top 1 t2.*
from table_2 t2
order by case
when t.date between t2.Date1 and t2.Date2
then 0
else 1
end
) as x
加1用于破译问题。表达得很好+1我很抱歉回复时间太长。刚刚回到网上。这很有效。我使用了我的问题的第一个代码。谢谢。@G83很乐意帮忙!谢谢你的问题编辑。这流动性要好得多。