You will have to play with this. You are having trouble mocking your sqlfiddle schema.
Select bar.* from ( SELECT * FROM vwuser AS a CROSS APPLY fnuserrank(a.userid) where rank != 'TERM' ) foo left join ( SELECT * FROM vwuser AS b CROSS APPLY fnuserrank(b.userid) where rank != 'TERM' ) bar on foo.empId = bar.empId and foo.MonitorDate > bar.MonitorDate where bar.empid is null
I always need to check that left newcomers are at higher dates. How it works, you do the left outer. Each EXCEPT line for each user has a line with a higher monitoring date. This one line is the one you want. I usually use an example from my code, but I am on the wrong laptop. for its work you can choose foo., bar. and look at the results and find the desired line and make the condition correct.
You can also make it easier to remember.
SELECT * FROM vwuser AS a CROSS APPLY fnuserrank(a.userid) ) foo join ( select empid, max(monitordate) maxdate FROM vwuser AS b CROSS APPLY fnuserrank(b.userid) where rank != 'TERM' ) bar on foo.empid = bar.empid and foo.monitordate = bar.maxdate
I usually prefer to use set-based logic over aggregate functions, but it works. You can also configure it by caching the results of your union of TVF into a table variable.
EDIT: http://www.sqlfiddle.com/#!3/613e4/17 - I mocked your TVF here. Apparently sqlfiddle did not like the "go".
select foo.*, bar.* from ( SELECT f.* FROM vwuser AS a join fnuserrank f on a.empid = f.empid where rank != 'TERM' ) foo left join ( SELECT f1.empid [barempid], f1.monitordate [barmonitordate] FROM vwuser AS b join fnuserrank f1 on b.empid = f1.empid where rank != 'TERM' ) bar on foo.empId = bar.barempid and foo.MonitorDate > bar.barmonitordate where bar.barempid is null
source share