SQL 查询以查找 2 个带有组的表之间的缺失数据

标签 sql sql-server

我已经尝试了几种方法来实现下一步,但必须有一种简单的方法。
假设我有 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/

相关文章:

python - 使用python将txt插入到sql server

sql-server - 在SQL Server中,如何将日期转换为M/D/YYYY格式的字符串? (没有前导零,不是 MM/DD/YYYY)

sql - 在 PostgreSQL 中使用 COALESCE 处理 NULL 值

c# - 关闭 SQL 连接但打开的连接不断增加

mysql - SQL 数据库帮助 - MySQL Workbench

mysql使用连接查询将两个表与注册表连接起来

SQL Server 查询列包含 id 列表

sql-server - 违反了对 null 的 UNIQUE KEY 约束

php - 使用第一个 MySQL 查询的结果从第二个表中提取数据

java - 如何在集成测试中设置保存点(使用内存中的 hsqldb)?