Sql 检查一列的值是否在另一列中
我是SQL新手,对下面的场景印象深刻,你们中的任何一位都可以在这方面提供帮助 我想检查产品的成分是否允许在生产线上使用,如果允许的话,那么生产线的名称就是可以生产的产品 表1Sql 检查一列的值是否在另一列中,sql,Sql,我是SQL新手,对下面的场景印象深刻,你们中的任何一位都可以在这方面提供帮助 我想检查产品的成分是否允许在生产线上使用,如果允许的话,那么生产线的名称就是可以生产的产品 表1 ProductionLine Allergen BB1 Tree nut BB1 Peanut BB1 Milk BB1 Wheat BB2 Tree nut BB2 Pean
ProductionLine Allergen
BB1 Tree nut
BB1 Peanut
BB1 Milk
BB1 Wheat
BB2 Tree nut
BB2 Peanut
BB2 Milk
BB2 soy
BB2 Egg
Product Ingredients
P1 Tree nut
P1 Peanut
P1 Milk
P1 soy
表2
ProductionLine Allergen
BB1 Tree nut
BB1 Peanut
BB1 Milk
BB1 Wheat
BB2 Tree nut
BB2 Peanut
BB2 Milk
BB2 soy
BB2 Egg
Product Ingredients
P1 Tree nut
P1 Peanut
P1 Milk
P1 soy
在这里,产品P1可以在BB2生产线上生产,因为BB2过敏原列表中允许所有成分。所以我想把结果设置为
预期结果
Product Ingredients ProductionLine
P1 Tree nut BB2
P1 Peanut BB2
P1 Milk BB2
P1 soy BB2
Product Ingredients ProductionLine
P1 Tree nut BB2
P1 Peanut BB2
P1 Milk BB2
P1 soy BB2
如果任何一种成分不允许在任何生产线上使用,那么我们就不能在该生产线上生产产品
预期结果
Product Ingredients ProductionLine
P1 Tree nut BB2
P1 Peanut BB2
P1 Milk BB2
P1 soy BB2
Product Ingredients ProductionLine
P1 Tree nut BB2
P1 Peanut BB2
P1 Milk BB2
P1 soy BB2
我现在拥有的代码
select I.[Product Name],I.[Ingredients], F.[Production Line]
from (select I.*,
count(*) over (partition by [Product Name],[Ingredients]) as num_products
from [dbo].[ProductIngredients] I
) I left join
[dbo].[ProductionFacilities] F
on I.[Ingredients] = F.allergen
group by I.[Product Name], F.[Production Line], I.num_products,I.[Ingredients]
having count(F.[Allergen]) = num_products;
试试这个:
SELECT p.*,l.ProductionLine
FROM table2 p
INNER JOIN (SELECT product,count(*) AS ingredients_cnt FROM table2 GROUP BY product) pc
ON p.product=pc.product
INNER JOIN table1 l
ON p.ingredients=l.Allergen
GROUP BY p.product,l.ProductionLine
HAVING COUNT(l.Allergen)=pc.ingredients_cnt
使用2个CTE计算每个产品和生产线的成分数量,并加入表2:
with
cte1 as (
select t2.product, count(*) counter
from table2 t2
group by t2.product
),
cte2 as (
select t2.product, t1.productionline, count(*) counter
from table2 t2 inner join table1 t1
on t1.allergen = t2.ingredients
group by t2.product, t1.productionline
)
select
t2.product, t2.ingredients, c2.productionline
from table2 t2
inner join cte1 c1 on c1.product = t2.product
inner join cte2 c2 on c2.product = t2.product and c2.counter = c1.counter
order by t2.product, c2.productionline
请参阅。
您尝试了什么?我很乐意为您提供帮助,但希望首先了解您的尝试。以下是我从(选择I.*,计数(*)中选择的I.[产品名称],I.[成分],F.[生产线]超过(按[产品名称],[成分])划分,作为[dbo]的num_产品[ProductComponents]I)我离开加入[dbo]。[ProductionFacilities]F on I.[Components]=F.过敏原组按I.[Product Name],F.[Production Line],I.num_产品,I.[Components]有计数(F.[Allogen])=num productsHi@Naveen,请编辑问题以包含此SQL。@Bruce,我已按要求在底部包含问题代码。您提出了相同的问题:并接受了答案。有什么问题吗?谢谢你的快速回复。我在下面得到了这个错误,当我在GROUPBY子句中包含该列时,我根本没有得到任何结果列“pc.components_cnt”在HAVING子句中无效,因为它未包含在聚合函数或GROUP BY子句中