我已经尝试了几种方法来实现下一步,但必须有一种简单的方法。
假设我有 cooking 食谱。每个食谱都有成分。
当 worker 准备一份食谱时,他们会分批进行。
我试图弄清楚如何找到缺少哪种成分的批次,稍后将其插入另一个表中,该表具有所有准备数据。目前,它只显示实际使用的成分的数据。
这是数据:
CREATE TABLE #Repipe
(
Recipe VARCHAR(1)
, Ingredient VARCHAR(2)
)
INSERT INTO #Repipe (Recipe, Ingredient)
VALUES
(1, 1)
, (1, 2)
, (1, 3)
, (1, 4)
CREATE TABLE #RecipePreparation
(
Recipe VARCHAR(1)
, Batch SMALLINT
, Ingredient VARCHAR(2)
)
INSERT INTO #RecipePreparation (Recipe, Batch, Ingredient)
VALUES
(1, 1, 1)
, (1, 1, 2)
, (1, 1, 3)
, (1, 1, 4)
, (1, 2, 1)
, (1, 2, 2)
, (1, 2, 3)
, (1, 2, 4)
, (1, 3, 1)
, (1, 3, 3)
, (1, 3, 4)
DROP TABLE #RecipePreparation
DROP TABLE #Repipe
如您所见,批号 3 缺少成分 #2。
最佳答案
如果我理解正确,您基本上想从 #Recipe
中获取所有记录。没有对应的表 (Recipe, Ingredient)
记录在 #RecipePreparation
?
如果我正确理解您的问题,这样的事情应该可以完成您的需求。查询未测试。
SELECT *
FROM (SELECT DISTINCT Recipe, Batch FROM #RecipePreparation) xrp
LEFT JOIN #Recipe r on r.Recipe = xrp.Recipe
LEFT JOIN #RecipePreparation rp on rp.Recipe = xrp.Recipe AND rp.Batch = xrp.Batch AND rp.Ingredient = r.Ingredient
WHERE rp.Ingredient IS NULL
关于SQL 查询以查找 2 个带有组的表之间的缺失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62960212/