【问题标题】:Build combined table from 2 uneven tables从 2 个不均匀的表中构建组合表
【发布时间】:2020-02-04 02:56:37
【问题描述】:

我有 2 个不均匀的表,我正在尝试将它们构建到 1 个表中,每个表都有一个要加入的日期和 ID,问题是有时 1 个表可以在第二个表中包含没有匹配日期的行

最初,表 2 似乎总是有表 1 的条目,所以我正在做一个左连接,它正在工作,但后来我发现右表有一些日期的条目但表 1 没有匹配日期的问题(即 19 和 20)我在 DATE 和 ID 加入

我需要建立一些包含所有日期的表格吗?

【问题讨论】:

  • 你需要一个完整的外连接来从两个表中获取数据。

标签: sql sql-server-2005


【解决方案1】:

一种选择是使用如下的完全外连接,并在表 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 

【讨论】:

  • 这看起来不错,我提供了简化的表格,两个表格每个都有大约 10 个列,有没有更简单的方法来包含两个表格中的所有列
  • 没关系,我只是个白痴,我只是按照正常的 a.col1、b.col1 等包括其余的列
猜你喜欢
  • 2022-06-10
  • 2016-10-18
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2016-12-16
  • 1970-01-01
相关资源
最近更新 更多