user2632905
user2632905

Reputation: 267

Query to combine data from 2 tables based on a condition for both the tables in SQL

I have 2 tables. ProfileInfo (ProfileID - PK) and EmployeeRole (EmpID - PK, ProfileID - FK). Both are connected using a ProfileID and both tables have LastUpdatedTimestamp Column. I need to fetch data from both the tables combined, using from and to lastupdated timestamp.

Sometimes both the tables get updated at the same time and most times only one get updated

. Here is what i have tried but it bring up data which is updated on both tables. Firstly, I tried join but it didn't work as much as i thought it would

     select emp.emp_id as EmpId from EmployeeRole emp 
     FULL OUTER JOIN ProfileInfo pi on emp.profile_id = pi.profile_id
     where emp.LST_UPDT_TS between '2017-09-18' and '2017-09-20' and 
     pi.LST_UPDT_TS between '2017-09-18' and '2017-09-20';

This brought emp ids that had changes on both the tables alone.

Table Details:
EmployeeRole Emp_ID PK, Profile_id FK, LST_UPDT_TS TIMESTAMP

ProfileInfo Profile_Id PK, Profile_name, LST_UPDT_TS TIMESTAMP

Example: If 2 records of ProfileInfo gets updated and 1 record of EmployeeRole gets updated. I need to get 3 emp_id considering both the records from ProfileInfo is not related to EmployeeRole record. If in case one of the record is related then I have to get 2 emp_id only.

I searched for similar answers for a short period but nothing worked. Please help.

Upvotes: 0

Views: 127

Answers (2)

user2632905
user2632905

Reputation: 267

This worked with some little tweeks from the initial query I changed.

select emp.emp_id as EmpId from EmployeeRole emp  
 JOIN ProfileInfo pi on emp.profile_id = pi.profile_id and
 ((emp.LST_UPDT_TS between '2017-09-18' and '2017-09-20') or 
 (pi.LST_UPDT_TS between '2017-09-18' and '2017-09-20'));

Thanks a lot @Serg and @Phil and @wildplasser

Upvotes: 0

Serg
Serg

Reputation: 22811

This is just an example, your conditions may vary

   SELECT
       -- common data
       COALESCE(emp.profile_id, pi.profile_id) as profile_id
      ,COALESCE(emp.LST_UPDT_TS, pi.LST_UPDT_TS) as LST_UPDT_TS
       -- emp role
      ,emp.emp_id as EmpId
       -- profile
      , pi.Profile_name
  FROM (SELECT * 
        FROM EmployeeRole 
        WHERE LST_UPDT_TS between '2017-09-18' and '2017-09-20') emp 
  FULL OUTER JOIN (
        SELECT * 
        FROM  ProfileInfo 
        WHERE LST_UPDT_TS between '2017-09-18' and '2017-09-20') pi
     -- rows matching predicate
      ON emp.profile_id = pi.profile_id
     AND emp.LST_UPDT_TS = pi.LST_UPDT_TS 

Upvotes: 1

Related Questions