我在查询中有这个连接语句
inner join ( select uas.UserId, max(uas.[TimeStamp]) as maxDate
from dbo.UserSt as uas group by uas.UserId ) as tb2
on tb2.UserId = e.UserId and tb2.maxDate < e.[TimeStamp]
如何首先检查maxDate
表中是否存在tb2
然后进行比较?
我需要,如果该表中没有maxDate,则从e.[TimeStamp]
答案 0 :(得分:0)
尝试这样的事情
left join ( select uas.UserId, max(uas.[TimeStamp]) as maxDate
from dbo.UserSt as uas group by uas.UserId ) as tb2
on tb2.UserId = e.UserId and
((tb2.maxDate < e.[TimeStamp] and tb2.maxDate is not null) or
(e.[TimeStamp]= e.[TimeStamp] and tb2.maxDate is null))
答案 1 :(得分:0)
您可以使用coalesce检查maxDate是否存在:
coalesce(tb2.maxDate, e.[TimeStamp]) -- will return e.[TimeStamp] if tb2.maxDate is null