此查询是大型查询的子集,其中我OUTER APPLY
表示一堆值,以便稍后过滤掉结果
我有一些数据:
Table: Items
ID | Material | Form
----------------------------------
1 | Aluminium | Sheets
------------------------------
1 | Carbon Steel | Bars
------------------------------
2 | Aluminium | Bars
我想找到满足给定输入的匹配ID。输入可以是三种形式之一,并且可以有一行或多行。当输入有多行时,该项必须满足所有行。输入的例子如下:
@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
我编写了一个可以处理输入类型1的查询和一个输入类型2的查询,但我需要将它们组合起来,并且能够处理输入类型3.
查询输入类型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
查询输入类型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
此时,我需要能够
任何帮助将不胜感激!此外,如果我可以解释任何事情,或者对此有任何更明确的解释,请告诉我。我尽量保持简洁和专注。
修改
这是查询所需的输出
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
所以只返回ID号码:
ID | Name | MaterialCondition.Material
-------------------------------------------
12 | Other Item | NULL
答案 0 :(得分:0)
到目前为止,我已经达到了一个功能状态,就像这样:
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
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)
)MaterailCondition2
--this makes sure that there isn't anything selected that does not match Material
WHERE MaterialCondition.Material IS NULL AND MaterialCondition2.Form IS NULL
这将正常工作,我有一个外部申请输入类型1和输入类型2,然后外部申请将照顾他们各自的输入类型3的部分。我想我只是希望包含这个一个OUTER APPLY