Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I combine two tables with different data and set value for CompanyC to all data in Table 2 and CompanyD has no relationship on Table 1. I want the Company C to set all data on Table 2.

   T1:                                 T2:

company     jobs                        emp_id  company     jobs     emp_name
-----------------------------------      -------------------------------------
CompanyA     IT                          1      CompanyA     IT        John
CompanyB     Business                    2      CompanyB     Business  Mike
CompanyC     Engineer                    3      CompanyD     Nurse     Mitch

And the result table would be like:

emp_id     company      jobs            emp_name           
----------------------------------------------     
1          CompanyA     IT                John     
1          CompanyC     Engineer          John  
2          CompanyB     Business          Mike      
2          CompanyC     Engineer          Mike
3          CompanyD     Nurse             Mitch
3          CompanyC     Engineer          Mitch

This is what I've tried

 SELECT  t2.emp_id, coalesce(t1.company_name, t2.company_name) AS company_name, 
    coalesce(t1.jobs, t2.jobs) AS jobs, 
    t2.emp_name, 
FROM Table1 t1  
    FULL OUTER JOIN      
    Table2 t2 ON t2.company = t1.company AND t2.jobs = t1.jobs
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

Simplest logic would be to divide it in small logics and then use union as follows:

Select t2.*
  From t1 join t2 on t1.company = t2.comapny and t1.jobs = t2.jobs
Union
Select t1.company, T2.jobs, T2.emp_name
  From t1 cross join t2
Where not exists (select 1 from t2 t22
                   Where t1.company = t22.comapny and t1.jobs = t22.jobs)
Union 
Select t2.* 
  From t2 where not exists ( select 1 from t1 
                              where t1.company = t2.comapny and t1.jobs = t2.jobs)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...