SQL Server Get Values where records not found

3duebb1j  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(145)

I have a table with top 3 products per industry

I also have a customer table with products they have purchased including what industry they belong to

I need a query which will join the tables and only return products not associated with the customer based on industry ie. CID 001 belongs to the Retail industry, it currently has product copper. Based on the industry table it is missing Silver and Gold.

Really stuck with this one and any help would be appreciated.

SQL 2016

Thanks in Advance

FYI.. having some issues with the formatting, 1st table below is the Industry, 2nd table is the Customer, 3rd is the Result(just for CID 001) of the query needed
| Industry | Product |
| ------------ | ------------ |
| Retail | Copper |
| Retail | Silver |
| Retail | Gold |
| Oil | Blue |
| Oil | Red |
| Oil | Gold |

CIDIndustryProduct
001RetailCopper
002RetailSilver
002RetailGold
003OilBlue
004OilRed
005OilGold
CIDIndustryProduct
------------------------------------
001RetailSilver
001RetailGold
41ik7eoe

41ik7eoe1#

The simple way is to use except .

In the first select you add all products using cross apply and then remove all you have in Customer using except

select c.CID, c.Industry, i.Product from Customer c
cross apply Industry i
where c.Industry = i.Industry
except
select CID, Industry, Product from Customer

eqqqjvef

eqqqjvef2#

Not sure if this helps, but if rename your second table to Orders, and add a Customers table that has the CID and Industry of the Customer, you could do the following

SELECT C.CID,
    I.Industry,
    I.product
FROM Industry I
INNER JOIN Customers C ON C.Industry = I.Industry
WHERE NOT EXISTS (
        SELECT O.CID
        FROM Orders O
        WHERE O.cid = C.cid
            AND O.Product = I.Product
        )
ORDER BY C.cid,
    I.Industry,
    I.Product

相关问题