Sql Server 2008 中三个表的匹配数据

Matching data from three tables in Sql Server 2008

我有三个 tables DespatchActivationReplaced,如下所示:

我想比较所有三个 table 的数据,以 Despatch table 为基础。

例如,如果我输入 LOTQty 作为 20,我应该根据以下计算收到结果:

  1. 它应该与Despatch中Lot 20下的所有ProductNo匹配table 与 ProductNoActivation table 中。如果找到匹配项(在本例中为 Product3、4、5 和 6),那么接下来它应该检查日期。

  2. 如果Dispatch Date匹配的ProductNo小于Activation Date才应该考虑。(产品 3 的发货日期小于激活日期。因此我们将其计为 1,对于所有其他产品也类似)。因此我们找到了 4 个匹配项。

  3. Product1 和 Product2 在激活 table 中未找到任何匹配项。对于此类产品编号,我们指的是 Replaced table。如果找到匹配项(在本例中为 Product1),它应该比较 Dispatch DateRecord Date。如果 Dispatch Date 小于 Record Date 那么我们才应该考虑数据(Product1 的 Dispatch date 小于 RecordDate。所以我们把它算作 1)。

  4. 所以现在总数量应该是 5 即 4 通过比较 Activation table 和 1 通过比较 Replaced table.

以上只是示例 table 个条目。我真正的 tables 包含更多的列,这些列被修剪以保持简单。我尝试准备查询,但无法找到满足我自己要求的逻辑。到目前为止我试过的查询如下:

select
(
    select distinct LOTQty
    from Despatch
    where LOTQty = '20'
)as LotQty

,(
    select COUNT(ProductNo)
    from Despatch
    where LOTQty = '20'
)as ApprovedQty

,(
    select distinct(DispatchDate)
    from Despatch
    where LOTQty = '20'
)as DispatchDate

,(
    select COUNT(ProductNo)
    from Activation
    where ProductNo in (select ProductNo from Despatch) and LotQty = '20'
)as Installed

结果如下:

已安装字段显示 4 作为。但是根据我上面的要求结果应该是 5。我怎样才能建立我的查询来满足我的要求?
非常感谢帮助,提前致谢。

EDIT1
在比较 Despatch table 的 ProductNoActivation Replaced,两者中可能存在相同 ProductNo 的条目ActivationReplaced tables。因此,查询应首先检查 Activation table。如果它在那里找到 ProductNo 的匹配项,则不应在 中搜索相同的 ProductNo Replacedtable。只有那些 ProductNoActivation table 中找不到匹配项或 DispatchDate大于Activation日期应匹配Replacedtable.

编辑 2

上图中ApprovedQty应该是6因为Despatch里面只有6个ProductNotable 第 20 批。

对于Installed它是这样的:

  1. 首先匹配来自DespatchProductNoProductNo Activation table 的 对于 Lot 20。它找到 5 个匹配项 (Product1,3,4,5,6)。但是作为 Product1 的 DispatchDate > ActivationDate,它将计数视为 4,忽略 Product1。
  2. 接下来它会尝试从 Despatch (Product1,2) 中找到剩余 ProductNo 的匹配项ReplacedProductNo。由于 Replaced table 没有 LotQty 列,它只匹配 ProductNo。它找到了 Product1 的匹配项(虽然 Product4 在这里也匹配,但因为它已经从 Activation 中考虑,所以不应该从 Replaced 中考虑)。现在 Product1 的 DispatchDate < RecordDate 所以它算作 1。
  3. 现在安装的总数是 Activation 的 4 个和 Replaced 的 1 个,使总数再次达到 5 .

我认为您可以使用左联接来执行此操作。尝试此查询,使用您的示例数据它会产生所需的输出,ApprovedQty 除外,但我不明白您是如何使用示例数据到达 12 的:

select 
    d.LOTQty, 
    ApprovedQty = count(d.ProductNo),
    d.DispatchDate,
    Installed = count(a.ProductNo) + count(r.ProductNo)
from 
    Despatch d 
left join 
    Activation a 
     on d.ProductNo = a.ProductNo 
    and d.DispatchDate < a.ActivationDate 
    and d.LOTQty = a.LOTQty
left join 
    Replaced r 
      on d.ProductNo = r.ProductNo 
     and d.DispatchDate < r.RecordDate
     -- only count Replaced when there is no match in Activation
     -- or DispatchDate is greater then ActivationDate
     and (a.ActivationDate is null or a.ActivationDate < d.DispatchDate)
where 
    d.LOTQty = 20
group by 
    d.LOTQty, d.DispatchDate

这将输出:

LOTQty  ApprovedQty DispatchDate    Installed
20      6           2013-08-07      5