检查日期是否存在然后进行比较

时间:2016-01-14 11:27:13

标签: sql sql-server tsql

我在查询中有这个连接语句

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]

获取值

2 个答案:

答案 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