外部加入不包括行

时间:2016-09-29 10:34:34

标签: sql sql-server

当我运行以下查询时,我会在结果中排​​除行,即使我知道它们应该在那里。我把它缩小到第5次加入:
                LEFT OUTER JOIN BDNDETL W ON                     W.CODE = B.WP
如果我删除该连接以及别名“W”引用的列,则会获得我期望的所有行。 W中有些行基于W.CODE = B.WP在B中没有匹配,但我认为LEFT OUTER条件会捕获这些,但事实并非如此。它似乎只是像INNER JOIN一样对待它。

SELECT
    p.p2 AS "Section",
    d.d9 AS "Alt WBS",
    p.p3 AS "Year",
    B.ca1 AS "WBS",
    concat(b.ca1,'/',b.ca2,'/',b.wp,b.descrip) AS "Work Package",
    B.WP,
    w.d9 AS "Cost Category",
    B.C3 AS "Provider",
    b.c1 AS "TType",
    w.d4 AS "WP GLA Cat",
    U.COSTSET,
    CONVERT(varchar, T.PD_FINISH, 101) period,
    SUM(A.ALLOWANCE1 + A.ALLOWANCE2 + A.ALLOWANCE3 + A.ALLOWANCE4 + A.ALLOWANCE5 + A.BASIC + A.BONUS + A.COMMODITY + A.DIRECT + A.ENHANCED + A.NIERS + A.OVERTIME + A.PENSION + A.PILON + A.REDUNDANCY) Value
FROM
    TPHASE A JOIN CAWP B ON
         B.PROGRAM = A.PROGRAM AND B.CAWPID = A.CAWPID
            JOIN MULTPROG X ON
                A.PROGRAM = X.SUBPROGRAM
            JOIN PROGRAM P ON
                A.PROGRAM = P.PROGRAM
            JOIN BDNDETL D ON
                D.CODE = B.CA1
            LEFT OUTER JOIN BDNDETL W ON
                W.CODE = B.WP
            JOIN COSTDETL U ON
                A.CLASS = U.CLASS
            JOIN RCUTOFF T ON
                A.DF_DATE BETWEEN T.PD_START AND T.PD_FINISH
WHERE
    X.MASTER = @master AND
    D.BREAKFILE = @wbsfile AND
    U.INSTANCE = @costdetlid AND
    T.INSTANCE = @cutoffid AND
    W.BREAKFILE = @wpbdn
GROUP BY
    p.p2,
    d.d9,
    p.p3,
    B.ca1,
    concat(b.ca1,'/',b.ca2,'/',b.wp,b.descrip),
    B.WP,
    w.d9,
    B.C3,
    b.c1,
    w.d4,
    U.COSTSET,
    T.PD_FINISH
;

2 个答案:

答案 0 :(得分:3)

你的where子句中有W.BREAKFILE = @wpbdn,左连接的空值无法通过此过滤器。

答案 1 :(得分:3)

WHERE子句中的这个条件:

    W.BREAKFILE = @wpbdn
没有匹配时

失败。为什么?因为W.BREAKFILENULL。您应该将其移动到适当的ON子句:

       LEFT OUTER JOIN BDNDETL W ON
            W.CODE = B.WP AND W.BREAKFILE = @wpbdn

而且,一条建议。当您混合innerleft联接时,我强烈建议您先将所有内部联接放在left join之后:

FROM TPHASE A JOIN
     CAWP B
     ON B.PROGRAM = A.PROGRAM AND B.CAWPID = A.CAWPID JOIN
     MULTPROG X
     ON A.PROGRAM = X.SUBPROGRAM JOIN
     PROGRAM P
     ON A.PROGRAM = P.PROGRAM JOIN
     BDNDETL D
     ON D.CODE = B.CA1 JOIN
     COSTDETL U
     ON A.CLASS = U.CLASS JOIN
     RCUTOFF T
     ON A.DF_DATE BETWEEN T.PD_START AND T.PD_FINISH LEFT JOIN
     BDNDETL W
     ON W.CODE = B.WP

这使逻辑更容易理解。我们的想法是内连接进行过滤,然后左连接说“保留所有这些行,如果匹配则添加这些额外的列”。