0

I came across this problem and after going around and around I ended up getting stuck. I have two tables with some columns in common and I would like to merge them into one:

enter image description here

I am not looking for the code necessarily but rather for some guidance towards the answer.

3
  • please post expected result,actual result as text,not images Commented Sep 17, 2017 at 4:03
  • Question updated Commented Sep 17, 2017 at 4:30
  • UNION ALL is a good start. Then you need aggregates to combine rows Commented Sep 17, 2017 at 12:54

1 Answer 1

1

You can get your desired result by full join-ing both tables and using coalesce and case as below.

SELECT COALESCE(t1.user1, t2.user1) AS "User", 
       t1.monday, 
       CASE 
         WHEN t2.tuesday = t1.monday THEN NULL 
         ELSE t2.tuesday 
       END as Tuesday
FROM   table1 t1 
       FULL JOIN table2 t2 
              ON t1.user1 = t2.user1 
ORDER  BY "user"; 

Result:

User    monday  Tuesday
----------------------
user1     gym     run
user1     run     
user2     gym     run
user3             gym
user4             gym
user5     gym     

You can heck the demo here

Sign up to request clarification or add additional context in comments.

2 Comments

That really helped a lot, but there is an issue: When user1 has run and gym on Mondays and Tuesdays, one of the exercises for Tuesday gets deleted by the CASE. If the case is removed then I duplicated rows.
@aeroalpha: I worked through the sample data provided in question. If you are looking for an answer for a different data set, kindly add another question. we will be happy to help. Thanks :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.