我有两个表,如下所示。我想根据下面的逻辑创建一个新变量(VALUE)并在第三个表中显示结果?我怎样才能在 T SQL 中做到这一点?
TABLE_1
ID, DATE
TABLE_2
ID, DATE1, DATE2
设置VALUE
的逻辑:
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 不匹配的行)的结果
),那么我们可以使用 left join
和 case
表达式:
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
如果您只想为 table_1
中的每一行分配一行,并且想知道 table_1.data
是否位于 table_2
中的任何对应行之间> 或否,那么我们可以使用 outer apply
来 select top 1
和 case
表达式:
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
关于T-SQL 检查一个表中的日期是否在另一个表中的两个日期之间,然后设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42964601/