Search code examples
sqloracle

Compare records within the same table and find missing setup


I'm trying to write an SQL in Oracle where I compare only two items in the same table and find the records where item2 is missing the warehouse setup where the warehouses exist in comparison to setup of Item1.

Please accept my thanks for your assistance towards adapting the SQL for which I almost have the answer but then I have to do manual adjustments to get the records looking good.

This is what my table looks like:

Warehouse Item
Alabama Item1
Arizona Item1
California Item1
Colorado Item1
Georgia Item1
Illinois Item1
Maine Item1
Montana Item1
Texas Item1
Alabama Item2
Arizona Item2
Colorado Item2
Illinois Item2
Texas Item2

and I'm trying to locate records like:

Warehouse Item
California Item2
Georgia Item2
Maine Item2
Montana Item2

The SQL I wrote is:

SELECT
  t1.Item, t1.Warehouse
FROM table t1
WHERE t1.Item = 'Item1'
and NOT EXISTS (SELECT 1 
                    FROM table t2
                   WHERE t2.Item1 <> t1.Item2
                     AND t2.Warehouse = t1.Warehouse
                     and t2.Item = ('Item2'));

Thank you again in advance.


Solution

  • This is pretty trivial problem. It can be solved by different ways. For example using LEFT JOIN:

    SELECT Items.Warehouse, 'Item2'
    FROM Items
    LEFT JOIN Items ItemsCopy ON 
        Items.Warehouse = ItemsCopy.Warehouse AND
        ItemsCopy.Item = 'Item2' 
    WHERE Items.Item = 'Item1' AND ItemsCopy.Warehouse IS NULL;
    

    or WHERE NOT EXISTS condition:

    SELECT Items.Warehouse, 'Item2'
    FROM Items
    WHERE Items.Item = 'Item1' AND NOT EXISTS (
        SELECT ItemsCopy.Warehouse 
        FROM Items ItemsCopy WHERE
            Items.Warehouse = ItemsCopy.Warehouse AND
            ItemsCopy.Item = 'Item2' 
    );
    

    Test the solutions on fiddle