2016-09-06 105 views
0

我有這個疑問,從源表返回27074行:查找SQL Server的兩個表之間的差異

SELECT 
    [DOC NO] 
    ,[LineNumber] 
    ,[SHEET] 
    ,[TestPkgNo] 
    ,[ITEM CODE] 
FROM 
    [excel].[dbo].[MTO2] 

而這一次(第二個表)

SELECT 
    DocumentNumber, LineNumber, SheetNumber, PackageNumber, ItemCode 
FROM 
    [SPMS2].[dbo].[Materials] 
JOIN 
    Lines ON materials.LineId = Lines.Id 
JOIN 
    MaterialDescriptions ON MaterialDescriptions.Id = Materials.MaterialDescriptionId 
JOIN 
    TestPackages ON TestPackages.Id = Materials.TestPackageId 

這將返回27032行。

我想找到兩個表之間的差異,我指的是結果應該是這樣的:

doc line sheet testpack sourcetable secondtable 
** * *  *   ok   not ok 
+0

向下投票評論! –

+0

簡單的左連接有什麼問題? –

+0

@ZoharPeled是的,它可以找到不同之處。 –

回答

1

這個查詢將返回所有存在於源表,但第二個不存在的記錄表。

SELECT 
    [DOC NO] 
    ,[LineNumber] 
    ,[SHEET] 
    ,[TestPkgNo] 
    ,[ITEM CODE] 
FROM 
    [excel].[dbo].[MTO2] sourcetable 

LEFT JOIN 
    (
     SELECT 
      DocumentNumber, LineNumber, SheetNumber, PackageNumber, ItemCode 
     FROM 
      [SPMS2].[dbo].[Materials] 
     JOIN 
      Lines ON materials.LineId = Lines.Id 
     JOIN 
      MaterialDescriptions ON MaterialDescriptions.Id = Materials.MaterialDescriptionId 
     JOIN 
      TestPackages ON TestPackages.Id = Materials.TestPackageId 
    ) secondtable 
ON sourcetable.[DOC NO] = secondtable.DocumentNumber -- Remove conditions that are not needed 
AND sourcetable.[LineNumber] = secondtable.LineNumber -- Remove conditions that are not needed 
AND sourcetable.[SHEET] = secondtable.SheetNumber -- Remove conditions that are not needed 
AND sourcetable.[TestPkgNo] = secondtable.PackageNumber -- Remove conditions that are not needed 
AND sourcetable.[ITEM CODE] = secondtable.ItemCode -- Remove conditions that are not needed 

WHERE secondtable.DocumentNumber IS NULL -- Assuming DocumentNumber is a non-nullable column