检查一列的值是否在另一列中

时间:2019-09-03 23:40:17

标签: sql

我是SQL的新手,在这种情况下感到震惊,请你们中的任何一个对此提供帮助。

我想检查产品的成分是否在生产线上允许,然后检查可以生产该产品的产品的生产线名称。

表1

ProductionLine       Allergen
  BB1          Tree nut
  BB1          Peanut
  BB1           Milk
  BB1           Wheat
  BB2          Tree nut
  BB2          Peanut
  BB2           Milk 
  BB2           soy
  BB2           Egg

表2

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

我现在拥有的代码

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;

2 个答案:

答案 0 :(得分:0)

尝试一下:

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 

答案 1 :(得分:0)

使用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

请参见demo