We help IT Professionals succeed at work.

Finding unmatched data between two sql tables

sleiman
sleiman asked
on
I have two SQL 2000 table:
Table 1: UserID, Date
Table2: UserID, DateOut, DateIn

UserID is used as a join between both tables
table1.Date needs to be matched as a date that falls between table2.Dateout and table2.datein
I need a sql code to first find recods that match in table2 and a seperate code to show all records from table1 that do not have a match in table2.
Comment
Watch Question

I'm not sure that I understand what you're trying to match as far as the date.  Does the UserID have to match AND the date needs to be between DateIn and DateOut?  Is this the case for both queries?

This will bring up all entries in Table 1 where the UserID is not in Table2:
SELECT * FROM table1 WHERE table1.UserID NOT IN (SELECT UserID FROM table2)

Top Expert 2008
Commented:
to get all records which falls within the date:

SELECT * from table1, table2 where table1.userid=table2.userid and table1.date>=table2.datein and table1.date<=table2.dateout

to get records that is not within range:
SELECT * from table1, table2 where table1.userid=table2.userid and (table1.date<table2.datein or table1.date>table2.dateout)
IN SQL Server you can use the INNER and OUTER joins to achieve what you are after.

"I need a sql code to first find recods that match in table2"
SELECT A.UserID, A.[Date]
FROM [Table 1] A
  INNER JOIN [Table 2] B
  ON A.Date BETWEEN DateOut AND DateIn

"seperate code to show all records from table1 that do not have a match in table2"
SELECT A.UserID, A.[Date]
FROM [Table 1] A
  LEFT OUTER JOIN [Table 2] B
  ON A.Date BETWEEN DateOut AND DateIn
WHERE B.UserID IS NULL

Cheers, Andrew
CERTIFIED EXPERT
Top Expert 2011
Commented:
Hello sleiman,

you should use use a left outer join then...


select Distinct a.*
       ,case when b.userid is null then 'Unmatched' else 'Matched' end as [Status]
  from table1 as a
  left outer join table2 as b
    pn a.userid=b.userid
  and a.date between b.dateout and b.datein
 order by a.userid





Regards,

Lowfatspread

Author

Commented:
thanks all.

LowFatspread's solution was best to do what I need in one show.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.