In our ERP database, there is 1 table for products called PRODUCTS
, which contains both kits and single SKU product information, and a table called PRODUCT_KIT_ITEMS
that contain the relationships between kit SKUs and their components.
In the PRODUCT table, each kit has a KIT_ID
on the parent SKU row and the PRODUCT_KIT_ITEMS
table lists each component PRODUCT_ID
from the PRODUCTS
table and the kit id of the parent SKU associated with it.
What I wanted was a list of all the SKUs of components associated with a parent SKU, both of which would be selected from the same column on the PRODUCTS
table.
This was the solution I came up with:
SELECT Parent.[PRODUCT_SKU] AS KitParent,
Child.[PRODUCT_SKU] AS ChildSKU
FROM [PRODUCT_KIT_ITEMS]
JOIN (
SELECT [PRODUCT_ID],[PRODUCT_SKU]
FROM [PRODUCTS]
) AS Child
ON Child.[PRODUCT_ID] = [PRODUCT_KIT_ITEMS].[PRODUCT_ID]
JOIN (
SELECT [PRODUCT_ID], [PRODUCT_SKU],[KIT_ID]
FROM [PRODUCTS]
WHERE [KIT_ID] IS NOT NULL
AND [KIT_ID] != 0
) AS Parent
ON Parent.[KIT_ID] = [PRODUCT_KIT_ITEMS].[KIT_ID]
ORDER BY Parent.[PRODUCT_SKU];
I'm a bit of a newbie and was wondering if there was a better way to accomplish this, for instance, without running two sub-queries on the PRODUCTS table.
Best Answer
If this is your current table schema:
You can get it by selecting all products with KIT_ID <> 0 (Parent rows) and then use CROSS APPLY to select all child rows that match parent KIT_ID.
Your current query:
dbfiddle here