I'm trying to do a query to find products that aren't on the customer's authorized products list, and it's breaking my brain.
Each customer has an authorized product group list, and within a product group each entry might consist of a Product ID, a Product Category ID, Vendor Number, Price Schedule ID, or Brand ID (all different columns on the Product record).
Many authorized product group lists have a mix of 2 or more kinds of entries, and often there's some overlap between the different columns used as selection criteria. Of course, there's a code on the product group list item that indicates which column the entry is based on, so it's easy enough to parse.
On the Product side, I'd be looking for products without an "Inactive" flag that aren't on the authorized list for each customer.
The tables look roughly like this:
Authorized List Items
While I have a fair bit of SQL experience, this has a level of complexity that's beyond me at this point...so part of what's messing me up is that I don't even know how to succinctly and accurately describe what I'm trying to do so I can do a search for it. I don't even know the appropriate tags for this question. Also, I forgot to mention earlier: T-SQL for SQL Server 2016R2.
Expected results would be a set of records with CustomerID and ProductID columns where the product wasn't in the authorized list for the customer and Inactive = 0. Ideally, this would be a view.
I've gotten as far as this query:
SELECT C.*, A.ItemRefNo, A.Type, CASE WHEN CA.ProductId IS NOT NULL THEN CA.ProductId WHEN B.ProductId IS NOT NULL THEN B.ProductId WHEN V.ProductId IS NOT NULL THEN V.ProductId WHEN P.ProductId IS NOT NULL THEN P.ProductId WHEN A.Type = 'ITEM' THEN A.ItemRefNo ELSE NULL END AS ProductId FROM Customer C INNER JOIN authorizedListItems A ON C.AuthorizedListId = A.ListKey LEFT JOIN products CA ON A.ItemRefNo = CA.CategoryKey AND A.Type = 'CATG' LEFT JOIN products B ON A.ItemRefNo = B.BrandKey AND A.Type = 'BRND' LEFT JOIN products V ON A.ItemRefNo = V.VendorKey AND A.Type = 'VNDR' LEFT JOIN products P ON A.ItemRefNo = P.PriceKey AND A.Type = 'PRIC'
The result I'd like to see is:
Let me say in advance, I know I wasn't filtering inactive items in the query and the results include superfluous columns.