比较两个相似表格中的数据

时间:2016-05-10 14:52:07

标签: sql-server

我试图比较两个具有相同结构的相似表格。所以我执行以下sql:

select * from mainTable g1 left join comparisonTable g2 on g2.SettingName=g1.SettingName

(表格列为:ID,SettingName,SettingValue,TimeStamp)

该查询工作正常,但我想将结果限制为仅显示G2.SettingValue为NULL或与G1.SettingValue不同的行。

所以我将上面的sql修改为:

 select * from mainTable g1 left join comparisonTable g2 on g2.SettingName=g1.SettingName where g1.SettingValue <> g2.SettingValue OR g2.SettingValue Is NULL

但是,这只返回满足第二个条件的行。如果我只是在没有

的情况下运行它
OR g2.SettingValue Is NULL

我根本没有任何行。但是很多行似乎都满足了这个查询。然而,它们并没有出现。

这个sql应该说明问题:

create table mainTable ([ID] [int] IDENTITY(1,1) NOT NULL, [settingname] [varchar](200) NULL, [settingvalue] [varchar](200))
create table comparisonTable ([ID] [int] IDENTITY(1,1) NOT NULL, [settingname] [varchar](200) NULL, [settingvalue] [varchar](200))
insert into maintable(SettingName, SettingValue) Values ('SettingName1','one'),('SettingName2','two'),('SettingName3','three')
insert into comparisonTable(SettingName, SettingValue) Values ('SettingName1','one'),('SettingName2','two'),('SettingName3','three')

然后运行:

 select * from mainTable g1 full outer join comparisonTable g2 on g2.SettingName=g1.settingName

然后运行:

insert into mainTable(SettingName, SettingValue) Values ('SettingName4','four') 

2 个答案:

答案 0 :(得分:1)

试试这个:

 -- differing values    
SELECT g1.*
, g2.SettingValue as g2SettingValue
FROM mainTable g1
INNER JOIN comparisonTable g2
ON g1.SettingName = g2.SettingName
AND g1.SettingValue <> g2.SettingValue
UNION ALL
-- missing matches
SELECT g1.*
, NULL
FROM mainTable g1
WHERE NOT EXISTS (
    SELECT 1
    FROM comparisonTable g2
    WHERE g1.SettingName = g2.SettingName

答案 1 :(得分:0)

以下应首先创建值的子集,其中mainTable和comparisonTable不同,然后执行连接以显示差异:

with cte(
  select * from mainTable
  EXCEPT
  select * from comparisonTable
)
select * from cte g1 left join comparisonTable g2 on g2.SettingName=g1.SettingName