【问题标题】:Microsoft SQL Server: Need to Compare Two Sets of ResultsMicrosoft SQL Server:需要比较两组结果
【发布时间】:2019-03-28 19:02:42
【问题描述】:

我有两个查询,每个查询都给我订单列表和每个订单上的订单项数量。我们正在迁移系统,一个来自源,另一个来自目标。我需要在它们之间做一些验证。

我想比较它们,以便我的结果是行数不匹配的订单列表。如果一个订单应该在目标中但不在,它也应该出现在列表中。

我已经为此奋斗了一整天,我无法思考如何处理它。

我们将不胜感激!

这是两个查询:

来源查询

select s.oNum, count(s.oNum) 
  from SourceTbl s
    left join PK_Master pk
      on pk.Num = s.oNum
  where s.oNum not in (select ordernum from tmpSalesOrders)
  group by s.oNum
order by s.oNum

目标查询

select p.oNum, count(p.oNum) 
  from BridgeTbl p
    left join TargetTbl t 
      on p.ToNum = t.orderID
  group by p.oNum
order by p.oNum

SourceTable 是一个超集,PK_Master 和 tmpSalesOrders 用于细化应该迁移的订单。

BridgeTbl 有一个名为 SoNum 的字段 = s.oNum 来链接源和目标。

我需要结果集中的源订单号(s.oNum)。

【问题讨论】:

  • 在这两个查询之间折腾EXCEPT,然后让'er rip。这将告诉您第一个查询输出的记录不在您的第二个查询中。您还可以使用oNum 将每个选择语句放入一个子查询中,并在您的计数不相等的情况下使用 LEFT OUTER JOIN。
  • 除了完美无缺。这对我来说是一个新的。谢谢!
  • 将您的评论放在答案中,以便我将其标记为已回答:D
  • 我很高兴这样做了。我已添加作为答案。

标签: sql sql-server select count


【解决方案1】:

在这两个查询之间折腾EXCEPT 并让'er rip。这将告诉您第一个查询输出的记录不在您的第二个查询中。

select s.oNum, count(s.oNum) 
  from SourceTbl s
    left join PK_Master pk
      on pk.Num = s.oNum
  where s.oNum not in (select ordernum from tmpSalesOrders)
  group by s.oNum
order by s.oNum

EXCEPT

select p.oNum, count(p.oNum) 
  from BridgeTbl p
    left join TargetTbl t 
      on p.ToNum = t.orderID
  group by p.oNum
order by p.oNum

EXCEPT 是“集合运算符”。在 TSQL 中,您可以设置 UNION, UNION ALLEXCEPT, and INTERSECT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多