从2个不均匀的表中构建组合表

问题描述 投票:0回答:1

我有2个不平坦的表,我试图将其构建为1个表,每个表都有要加入的日期和ID,问题是有时1个表在第二个表中可能有没有匹配日期的行

最初,表2似乎总是在表1上有一个条目,所以我在进行左连接,这是可行的,但是随后我发现了一个问题,其中右表具有某些日期的条目,但表1没有匹配的日期(即19和20)我是在DATE和ID加入的]

enter image description hereenter image description hereenter image description here

我是否需要建立一个包含所有日期的表?

sql sql-server-2005
1个回答
0
投票

一种选择是如下所述使用完全外部联接,并在以下表1或表2中不存在记录时使用用例语句填充值。

select case when a.date is not null then 
                 a.date
            else b.date
        end as date
        ,case when a.id is not null then 
                   a.id
              else b.id
          end as id
       ,case when a.name is not null then 
                   a.name
              else b.[full name]
          end as name 
        ,a.[Time Logged In]
        ,b.vol
  from table1 a
full outer join table2 b
     on a.date=b.date
    and a.id=b.id 
© www.soinside.com 2019 - 2024. All rights reserved.