Where子句包含可能不存在的信息

时间:2013-10-15 18:19:13

标签: sql sql-server tsql

我有一个带有电话的临时表,需要根据日志表进行检查。

临时表

  • Phone varchar(20)

日志表

  • Phone varchar(20)
  • [状态] varchar(20)
  • ChangeDate DateTime

日志表数据

  • 日志表中的每部手机的状态始终为“已添加”
  • 但并非每部手机都具有“已删除”状态

示例:

  • 电话状态更改日期

  • 3054444444已添加10-12-2012

  • 4445556666已添加10-12-2012
  • 3054444444已删除11-12-2012

Where子句有2个部分,它们都必须为真

1。 Temp.Phone可以在以下时间加入:

  • @Date大于或等于log.ChangeDate
  • log.Status ='已添加'

这是一个棘手的部分....我无法弄清楚

2。加入还需要确保:

  • @Date小于log.ChangeDate
  • 当log.Status ='已删除'
  • log.Status ='removed'可能不存在,所以我需要检查它是否存在然后是真的,如果不存在,那么忽略或生成一个真实的

SQL声明

SELECT *
FROM #temp t
JOIN log l
ON t.Phone = l.Phone
WHERE  (l.ChangeDate < = @Date AND  l.Status = 'Added')    
  AND 
       (l.ChangeDate > @Date AND l.Status = 'Removed') --may not exist, but ALSO has to be true

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT *
FROM #temp t
JOIN log l
  ON t.Phone = l.Phone
WHERE (l.ChangeDate < = @Date AND  l.Status = 'Added')    
  AND (
   (l.ChangeDate > @Date AND l.Status = 'Removed')
  or not exists(
       select 'removed'
       from log l2
       where l2.phone = t.phone
       and l2.ChangeDate > @Date AND l2.Status = 'Removed'
    )
  )

答案 1 :(得分:1)

您可以第二次加入日志表或使用NOT EXISTS子句,但请务必检查日期不等式......

SELECT *
FROM #temp t
    INNER JOIN log l
    ON t.Phone = l.Phone
    AND l.Status = 'Added'
    AND l.ChangeDate <= @Date
WHERE NOT EXISTS (
    SELECT *
    FROM Log
    -- This makes sure that the phone wasn't removed in between the date it was
    -- added and the date you are querying.
    WHERE Log.ChangeDate > l.ChangeDate
        AND Log.ChangeDate <= @Date
        AND Log.Phone = t.Phone
        AND Log.Status = 'Removed'
  )