【问题标题】:Find the mismatch columns from two tables with same structure从具有相同结构的两个表中查找不匹配的列
【发布时间】:2021-09-22 22:06:16
【问题描述】:

我有两个结构相同的表。我必须根据 id 和 year 组合在两个表中找到不匹配的列。下面是表结构:

id 和 year 是两个表中的主键。

================================================ ============== 为table1创建表和插入脚本:

create table table1 (id int, year int, name varchar(50), stat varchar(50), PRIMARY KEY (id,year));

insert into table1 values (1,2021,'Aman','L');
insert into table1 values (2,2021,'Ankit','H');
insert into table1 values (3,2021,'Rahul','G');
insert into table1 values (4,2021,'Gagan','L');

================================================ ============== 为table2创建表并插入脚本:

create table table2 (id int, year int, name varchar(50), stat varchar(50), PRIMARY KEY (id,year));

insert into table2 values (1,2020,'Aman','H');
insert into table2 values (2,2020,'Anuj','M');
insert into table2 values (3,2020,'Rahul','G')
insert into table2 values (4,2020,'Abhi','L')

================================================ ==============

预期输出:

例如,与来自 table2 的 id = 1 和 year = 2020(table1 year -1)相比,第一个表的 id = 1 和 year = 2021 应该返回不同的统计数据。

table1 中的 id = 2 和 year = 2021 与 table2 中的 id = 2 和 year = 2020 相比,应该返回该名称并且 stat 不同。

我需要将 table2 中的 year-1 与 table1 的年份列进行比较。

谁能帮我处理 sql 或 DB2 查询或过程,我该怎么做。

【问题讨论】:

  • 以格式化文本 CREATE TABLE + INSERT INTO 脚本的形式提供示例数据。为此数据提供所需的输出。
  • @Akina 在问题中提到了创建和插入语句。
  • 好吧,但是想要的输出在哪里呢?是否完整,格式为表格形式?

标签: db2


【解决方案1】:

听起来你需要一个简单的加入

select * 
from table1 t1
     join table2 t2 
       on t1.id = t2.id
          and t1.year = t2.year + 1
where t1.stat <> t2.stat
      or t1.name <> t2.name --if you want this?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多