T-SQL在SQL Server 2012中的JOIN中丢失记录

时间:2014-01-21 17:13:36

标签: tsql sql-server-2012

我有两个表我试图从SQL Server 2012中提取数据。我正在从BOIN表中丢失记录,从JOIN到ItemNumber上的PO表。我该如何解决这个问题? BO表查询最初提取309行,完整查询提取280行。我知道在PO表中存在的项目不存在于BO表中,但是我仍然需要在最终结果中看到这些项目,所以我可以说它们是下落不明的。

SELECT
    a.ItemNumber,
    a.BOQty,
    a.TtlBO$,
    MIN(po.PBDUE) AS PODueDate
FROM
    dbo.PO po
    RIGHT JOIN
(SELECT
    bo.ItemNumber,
    SUM(bo.BOQty) AS BOQty,
    SUM(bo.ExtPrice) AS TtlBO$
FROM
    dbo.BO bo
GROUP BY
    bo.ItemNumber
)a
ON a.ItemNumber = po.PBITEM
WHERE po.PBTYPE <> 'R'
  AND po.PASTAT <> 'X'
GROUP BY
    a.ItemNumber,
    a.BOQty,
    a.TtlBO$
ORDER BY
    ItemNumber

1 个答案:

答案 0 :(得分:0)

以下是我能够得到我需要的东西:

SELECT
        a.ItemNumber,
        a.BOQty,
        a.TtlBO$,
        MIN(po.PBDUE) AS PODueDate
    FROM
        dbo.PO po
        RIGHT JOIN
    (SELECT
        bo.ItemNumber,
        SUM(bo.BOQty) AS BOQty,
        SUM(bo.ExtPrice) AS TtlBO$
    FROM
        dbo.BO bo
    GROUP BY
        bo.ItemNumber
    )a
    ON a.ItemNumber = po.PBITEM AND po.PBTYPE <> 'R' AND po.PASTAT <> 'X'
      OR po.PBITEM IS NULL
    GROUP BY
        a.ItemNumber,
        a.BOQty,
        a.TtlBO$
    ORDER BY
        ItemNumber