【问题标题】:How to compare two tables in SQL Server [closed]如何比较 SQL Server 中的两个表 [关闭]
【发布时间】:2020-05-30 17:57:35
【问题描述】:

我需要比较 SQL Server 中的两个表,如下所示,我需要比较两列。

表1

SystemName, ReconID

hostname1,Recon1
hostname2,Recon2
hostname7,Recon3

表2

AssetName, ReconID

hostname1,Recon1
hostname2,Recon6
hostname3,Recon3

比较条件:

  1. SystemName = AssetName AND ReconID ReconID
  2. SystemName AssetName AND ReconID = ReconID
  3. SystemName = AssetName AND ReconID = ReconID

请帮助我处理 SQL 查询。 我已经尝试过以下事情。

【问题讨论】:

标签: sql sql-server stored-procedures


【解决方案1】:

如果你想查看数据,那么你可以这样做:

select "Condition 1" as condition
     , SystemName
     , AssetName
     , Table1.ReconID as "Table1_ReconID"
     , Table2.ReconID as "Table2_ReconID"
from Table1, Table2
where SystemName = AssetName AND Table1.ReconID <> Table2.ReconID
union 
select "Condition 2" as condition
     , SystemName
     , AssetName
     , Table1.ReconID as "Table1_ReconID"
     , Table2.ReconID as "Table2_ReconID"
from Table1, Table2
where SystemName <> AssetName AND Table1.ReconID = Table2.ReconID
union
select "Condition 3" as condition
     , SystemName
     , AssetName
     , Table1.ReconID as "Table1_ReconID"
     , Table2.ReconID as "Table2_ReconID"
from Table1, Table2
where SystemName = AssetName AND Table1.ReconID = Table2.ReconID
order by condition

在相交的情况下,使用“union all”而不是“union”。

【讨论】:

  • 请始终使用 ANSI 连接语法
猜你喜欢
  • 2017-11-17
  • 2012-08-01
  • 1970-01-01
  • 2017-11-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多