T-SQL:加入两个表

时间:2017-09-17 03:56:41

标签: sql sql-server

我遇到了这个问题,在四处走动之后,我最终陷入困境。我有两个共同列的表,我想将它们合并为一个:

enter image description here

我不是必须寻找代码,而是寻求答案的一些指导。

1 个答案:

答案 0 :(得分:1)

您可以通过full join-ing两个表格并使用coalescecase获得所需的结果,如下所示。

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"; 

<强>结果:

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

您可以修改演示 here