Filter rows if value exists in different columns
-
10-03-2021 - |
Question
We're on SQL Server 2016 and 2019
I have a data-set where I'm rolling up a parent/child relationship. I'm doing this because some of the parent rows will return a SalesValue
of 0 when their children will the value we're looking for.
Here's my query:
SELECT ART.StockCode
, BOM.Component
, ART.QtyInvoiced
, ART.Invoice
, ART.SalesValue
, ART2.SalesValue
FROM TABLE1 ART
JOIN TABLE2 IM
ON IM.StockCode = ART.StockCode
LEFT OUTER JOIN TABLE3 BOM
ON BOM.ParentPart = ART.StockCode
AND IM.KitType = 'K'
LEFT OUTER JOIN TABLE4 ART2
ON ART2.StockCode = BOM.Component
AND ART2.Invoice = ART.Invoice
And the data it returns
StockCode Component QtyInvoiced Invoice SalesValue SalesValue2
315128 NULL 1.000000 1 154.32 NULL
317324 NULL 1.000000 1 68.31 NULL
317350 NULL 1.000000 1 428.90 NULL
318482 NULL 1.000000 1 171.24 NULL
320058 NULL 1.000000 1 28.58 NULL
320058 NULL 1.000000 1 28.58 NULL
320058 NULL 1.000000 1 28.58 NULL
900550 NULL 1.000000 1 2396.08 NULL
900572 NULL 1.000000 1 1448.84 NULL
900581 NULL 1.000000 1 2017.96 NULL
901012 900581 1.000000 1 0.00 2017.96
901012 317350 1.000000 1 0.00 428.90
901012 317324 1.000000 1 0.00 68.31
901062 900572 1.000000 1 0.00 1448.84
901062 318482 1.000000 1 0.00 171.24
What I'm trying to do is exclude any StockCode
that has a value in the Component
field that has the same Invoice
number
In the example above, we're looking to exclude stock codes 900581, 317350, 317324, 900572, and 318482 because they already exist in the Component
field.
Here's what I'm going for:
StockCode Component QtyInvoiced Invoice SalesValue SalesValue2
315128 NULL 1.000000 1 154.32 NULL
320058 NULL 1.000000 1 28.58 NULL
320058 NULL 1.000000 1 28.58 NULL
320058 NULL 1.000000 1 28.58 NULL
900550 NULL 1.000000 1 2396.08 NULL
901012 900581 1.000000 1 0.00 2017.96
901012 317350 1.000000 1 0.00 428.90
901012 317324 1.000000 1 0.00 68.31
901062 900572 1.000000 1 0.00 1448.84
901062 318482 1.000000 1 0.00 171.24
Solution
WITH cte AS (your query)
SELECT t1.*
FROM cte t1
WHERE NOT EXISTS ( SELECT NULL
FROM cte t2
WHERE t1.StockCode = t2.Component )
This works by wrapping your original query up into a CTE, then only returning rows from it if there are no other rows where the Component column is equal to the StockCode column.