0

I have this query that returns 27074 rows from the source table:

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

And this one (second table )

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

This returns 27032 rows.

I want to find the difference between two tables, I mean the result should be like this :

doc line sheet testpack  sourcetable  secondtable
**   *   *      *          ok           not ok 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ehsan Akbar
  • 6,977
  • 19
  • 96
  • 180

1 Answers1

1

This query will return all the records that exist in the source table but doesn't exist in second table.

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
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121