T-SQL 检查一个表中的日期是否在另一个表中的两个日期之间,然后设置值

标签 t-sql sql-server-2012

我有两个表,如下所示。我想根据下面的逻辑创建一个新变量(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_1id 不匹配的行)的结果),那么我们可以使用 left joincase 表达式:

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 applyselect top 1case 表达式:

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/

相关文章:

sql - 在 SQL Server 中聚合日期

asp.net - 使用gridview时"must declare scalar variable"

c# - MSSQL超时错误

sql - 使用TSQLUNIT进行SQL单元测试: don't you need to duplicate your SQL code?

sql - SQL Server 中的 UTC 和偏移日期时间比较

SQL Between 子句返回超出界限的值的行

sql-server - 使用 SQL Azure 数据库时存储过程是否有任何差异/限制

sql - 删除表中记录数给定的记录数

statistics - SQL Server Index Usage Stats 多久更新一次,是什么触发了它?

sql - 需要帮助将行转列