This query is a subset of a large query, where I’m OUTER APPLY‘ing a bunch of values, to filter out results later
I’ve got some data:
Table: Items
ID | Material | Form
----------------------------------
1 | Aluminium | Sheets
------------------------------
1 | Carbon Steel | Bars
------------------------------
2 | Aluminium | Bars
I want to find the matching IDs, that satisfy a given input. The input can be in one of three forms, and can have one or many rows. When an input has multiple rows, the item must satisfy ALL rows. Examples of input are given below:
@Input type 1: (just a material, one or multiple allowed)
Material | Form
-------------------
Aluminium | NULL
@Input type 2: (material and a form, one or multiple allowed)
Material | Form
-------------------
Aluminium | Sheets
@Input type 3: (one or more material and form, with one or more materials)
Material | Form
-------------------
Aluminium | Sheets
Carbon Steel | NULL
I’ve written a query that can handle input type 1 and a query for input type 2, but I need to combine them, and be able to handle input type 3.
Query for Input Type 1:
Select *
From table
OUTER APPLY(
SELECT top(1) i.Material
FROM @Input i --Input type 1
WHERE i.Material NOT IN
(SELECT items.Material
FROM Items
WHERE items.id = table.id)
)MaterailCondition
--this makes sure that there isn't anything selected that does not match Material
WHERE MaterialCondition.Material IS NULL
Query for Input Type 2:
Select *
From table
OUTER APPLY(
SELECT top(1) i.Material, i.Form
FROM @Input i --Input type 1
WHERE i.Material NOT EXISTS
(SELECT *
FROM Items
WHERE items.id = table.id
AND items.Material = i.Material
AND items.Form = i.Form)
)MaterailCondition
--this makes sure that there isn't anything selected that does not match Material
WHERE MaterialCondition.Form IS NULL
Again, at this point, I need to be able to
- Combine the queries into the same outer apply block
- Accomodate Input Type 3
Any help would be greatly appreciated! Also, if I can explain anything, or be any clearer about any aspect of this, please let me know. I tried to keep it as short and focused as possible.
EDIT
Here would be the desired output from the query
ID | Name | MaterialCondition.Material
-------------------------------------------
23 | Some Item | (any text, such as 'Carbon Steel') <-- This is not a match
12 | Other Item | NULL <-- This IS a match
--(the where clause will filter these out, by saying)
WHERE MaterialCondition.Material IS NULL
So just ID number 12 is returned:
ID | Name | MaterialCondition.Material
-------------------------------------------
12 | Other Item | NULL
So far I’ve gotten to a state that functions, like this:
This will work properly, and I’ve got an outer apply for input type 1 and input type 2, then the outer applys will take care of their respective parts of input type 3. I guess I was just hoping to contain this logic inside of one
OUTER APPLY