[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 848
  • Last Modified:

Finding unmatched data between two sql tables

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.
0
sleiman
Asked:
sleiman
4 Solutions
 
franked_itCommented:
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)

0
 
ee_rleeCommented:
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)
0
 
TextReportCommented:
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
0
 
LowfatspreadCommented:
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
0
 
sleimanAuthor Commented:
thanks all.

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

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now