Sql-server – Finding the first occurrence where id don’t match

sql servert-sql

I’m trying to find the first occurrence of SNum where the VerNum don’t match. In this case it should point to SNum = 300 as VerNum 12 is not present.

DROP TABLE #temp1
DROP TABLE #temp2

CREATE TABLE #temp1 (VerNum INT, SNum INT)

INSERT INTO #temp1 
VALUES (11,100), (12,100), (11,200), (12,200), (11,300)


CREATE TABLE #temp2 (VerNum INT)

INSERT INTO  #temp2 
VALUES (11), (12) 


SELECT * FROM #temp1
SELECT * FROM #temp2

A full join is not working, i can loop through the table and get the result I am after, but there must be a better way. Any help is appreciated.

Best Answer

How about something like this?

select top 1 snum 
from #temp1 
group by SNum
having count(*) < (select count(*) from #temp2) 
order by snum asc

This could work if you're sure that there are no duplicates vernum for the same snum

This by the way, i think is a more solid solution:

select top 1 coalesce(a.snum, b.snum) as result
from #temp1 a full join #temp1 b on a.SNum = b.SNum and a.VerNum <> b.VerNum
where a.VerNum is null or b.VerNum is null

I didn't test them much, only with the data you provided, so be careful!