我有一个带有电话的临时表,需要根据日志表进行检查。
临时表
日志表
日志表数据
示例:
电话状态更改日期
3054444444已添加10-12-2012
Where子句有2个部分,它们都必须为真
1。 Temp.Phone可以在以下时间加入:
这是一个棘手的部分....我无法弄清楚
2。加入还需要确保:
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
答案 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'
)