访问 SQL 查询,该查询在 where 子句中使用一个 table 中的字段来创建计算字段

Access SQL query that uses a field from one table within where clause to create a calculated field

这真的没有那么复杂,但我无法理解它。我进行了彻底的搜索,但即使是为这个问题想出一个搜索字符串或标题也很困难。解释说明一切:

  1. Table "labelDrops" 有字段 "PO" 和 "Qty"(以及其他不相关的字段)
  2. Table "imageLiveCount" 有字段 "PO"
  3. 我想计算 imageLiveCoount.PO = labelDrops.PO 的实例 (count(imageLiveCount.id)) ,然后从 "QTY" 中减去它以创建一个名为 "QtyLeft".
  4. 结果基本上看起来像 "SELECT PO, Qty, answerToThisQuestion AS QtyLeft FROM labelDrops"

首先创建一个查询,为您提供 imageLiveCount table:[=12 中每个 PO 的计数=]

SELECT i.PO, Count(*) AS CountOfInstances
FROM imageLiveCount AS i
GROUP BY i.PO

如果该查询 returns 您想要什么,请将其加入 labelDrops table 并计算 QtyLeft :

SELECT
    l.PO,
    l.Qty,
    (l.Qty - sub.CountOfInstances) AS QtyLeft
FROM
    labelDrops AS l
    INNER JOIN
        (
            SELECT i.PO, Count(*) AS CountOfInstances
            FROM imageLiveCount AS i
            GROUP BY i.PO
        ) AS sub
    ON l.PO = sub.PO