Here is an example of how you can write the query. This query gives you both kinds. You can remove one or the other clause from the HAVING section to pick one type of the other. You can copy the code and run from an SSMS window to see how it behaves:create table #A(id int);create table #B(CodeId int, dt datetime) insert into #A values (1),(2),(3),(4),(5);insert into #B values (1,'20120401'),(1,'20000101'),(2,'20120501'),(3,'20000307'),(3,'20041212');select a.id, max(b.dt)from #A a left join #B b on a.Id = b.CodeIdgroup by a.Idhaving max(b.dt) < dateadd(yy,-5,getdate()) or max(b.dt) is null drop table #A,#B;