简体   繁体   English

T-SQL查找其他数据库中缺少的项目

[英]T-SQL Finding Missing item from another database

I have 2 databases for 2 different system. 我有2个不同系统的数据库。 EDI system and ERP System as below EDI系统ERP系统如下

I would like to know all the ProductId that are not in ErpOrderItem table for all the orders in EDI System Order table 我想知道EDI系统订单表中所有订单的所有不在ErpOrderItem表中的ProductId

A. EDI System

Order
----
1. OrderId
2. OrderDate

OrderItems
---------
1. OrderItemId

2. OrderId

3. ProductId

Order_Erp
------
1. OrderId
2. ErpDocNum


ERP System


ErpOrder
-------
1. ErpDocNum
2. DocEntry

ErpOrderItem
----
1. DocEntry
2. ProductId

For example , I would like to know all items that in OrderItems which are not available in ErpOrderItem for orders that linked by order key and ErpDocNum. 例如,我想知道OrderItems中的所有项目在ErpOrderItem中不可用于按订单键和ErpDocNum链接的订单。 These 2 systems are linked by ErpDocNum in Order_Erp table 这两个系统由Order_Erp表中的ErpDocNum链接

I have tried as below but it's not giving the result I am after. 我试过如下,但它没有给出我追求的结果。

select * from edi.Orders ODR
INNER JOIN edi.Order_Erp ERDR ON  ODR.OrderId = ERDR.OrderId
INNER JOIN edi.OrdersItems ODRL ON ODR.OrderId = ODRL.OrderId
INNER JOIN ErpOrder ON ERDR.ErpDocNum = ErpOrder.ErpDocNum
INNER JOIN ErpOrderItem ON ErpOrder.DocEntry = ErpOrderItem.DocEntry
where ErpOrder.ProductId != ODRL.Productid collate SQL_Latin1_General_CP1_CI_AS

As per the table schema provided, the column mentioned in your on condition is wrong (ON ERDR.ErpOrderNumber = ErpOrder.DocNum ) 根据提供的表模式,您的on条件中提到的列是错误的(ON ERDR.ErpOrderNumber = ErpOrder.DocNum

SELECT * 
FROM edi.Orders ODR
  INNER JOIN edi.Order_Erp ERDR ON  ODR.OrderId = ERDR.OrderId
  INNER JOIN edi.OrdersItems ODRL ON ODR.OrderId = ODRL.OrderId
  INNER JOIN ErpOrder ON ERDR.ErpDocNum = ErpOrder.ErpDocNum
   INNER JOIN ErpOrderItem ON ErpOrder.DocEntry = ErpOrderItem.DocEntry
WHERE ErpOrder.ProductId != ODRL.Productid collate SQL_Latin1_General_CP1_CI_AS

If I understand your question correctly, what you are after is a list of all products that are in your EDI system but not in your ERP system? 如果我正确理解您的问题,您所追求的是您的EDI系统中但不在ERP系统中的所有产品的列表? If that is all you want then this should be all you need to get those results. 如果这就是你想要的,那么这应该是获得这些结果所需的全部内容。 If I'm not correctly understanding your requirements it is usually helpful to provide an example of your tables and the expected results for clarification 如果我没有正确理解您的要求,那么提供一个表格示例和预期结果通常很有帮助

SELECT DISTINCT ProductID
FROM edi.OrderItems AS OI
WHERE NOT EXISTS
(
    SELECT 1
    FROM ErpOrderItem AS EOI
    WHERE OI.ProductID = EOI.ProductID
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM