我有两个表格如下所示。我想根据下面的逻辑创建一个新变量(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
答案 0 :(得分:3)
如果您希望查看table_1.id = table_2.id
(以及table_1
上没有匹配的id
行的所有行的结果,那么我们可以使用{{1}和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
之间的任何对应行,那么我们可以使用{{ 1}}到table_2
和outer apply
表达式:
select top 1