假设我有以下表格:
##TABLE1
FirstName, LastName, AsOfDate, NoOfEpisodes
Bart, Simpson, 07/01/2018, 123
Lisa, Simpson, 03/01/2018, 110
##TABLE2
FirstName, LastName, AsOfDate, NoOfEpisodes
Bart, Simpson, 08/01/2018, 123
Lisa, Simpson, 08/01/2018, 130
如果我运行以下SQL命令以查找两个表之间的差异:
select * from ##TABLE2
except (select * from ##TABLE1)
结果将是
FirstName, LastName, AsOfDate, NoOfEpisodes
Bart, Simpson, 08/01/2018, 123
Lisa, Simpson, 08/01/2018, 130
我想进行此比较,但忽略AsOfDate
字段,但将其保留在最终结果中。如果我执行此SQL:
select FirstName, LastName, NoOfEpisodes
from ##TABLE2
except (select FirstName, LastName, NoOfEpisodes from ##TABLE1)
结果看起来像这样
FirstName, LastName, NoOfEpisodes
Lisa, Simpson, 130
但是我需要它看起来像这样
FirstName, LastName, AsOfDate, NoOfEpisodes
Lisa, Simpson, 08/01/2018, 130
显然,这是一组数据示例。生产中的数据可能包含20-30列,我最多只想排除几列。我希望可能有类似“ IGNORE”或“ NOT IN”的功能可以应用到SQL脚本中,以排除仅两列。
答案 0 :(得分:1)
那怎么办?
SELECT T1.FirstName, T1.LastName, T2.AsOfDate, T2.NoOfEpisodes
FROM ##TABLE1 T1
INNER JOIN ##TABLE2 T2
ON T1.FirstName = T2.FirstName AND T1.LastName = T2.LastName
WHERE T1.NoOfEpisodes != T2.NoOfEpisodes
好的,根据您的评论。如果我们选择CTE,该怎么办?
;WITH ex as (
select FirstName, LastName, NoOfEpisodes
from ##TABLE2
except (select FirstName, LastName, NoOfEpisodes from ##TABLE1)
)
SELECT ex.FistName, ex.LastName, ex.NoOfEpisodes, T2.AsOfDate
FROM ex
INNER JOIN ##TABLE2 T2
ON ex.FirstName = T2.FirstName AND ex.LastName = T2.LastName
如果列要处理的列过多,则可以使用excel为您编写SQL where子句。打开SSMS和“选择前1000行”,这将为您提供该表的列的列表。复制该列表并将其粘贴到excel的A列中。然后在B列中添加以下功能:
="OR T1." & A1 & " != T2." & A1
将该函数复制到B中的所有行,然后可以复制值,该值将是一长串条件,可放入where子句中。您可以使用SELECT列表来做到这一点:
="T2." & A144 & ", "