JOIN查询中出现意外的NULL

时间:2017-07-26 08:45:48

标签: sql join

我在查询中使用了3个表:2个用INNER JOIN,第3个用LEFT JOIN

但是,在NULL条件执行时,我收到了一些LEFT JOIN条记录。来自购买行(PL_ TABLE)`不应该是这种情况。

任何人都可以推荐查询中的更改,以使用实际值替换记录中的NULL值吗?

抱歉,我找不到附加样本表数据的任何选项。

查询

SELECT
    pih.[PO Number], 
    pih.[Pre-Assigned No_] as [Invoice No],
    pil.[Document No_],
    pil.[Description] as [Reason For Discrepency],
    pil.[Line No_],
    pl.[No_] as [Item No],
    pl.[Vendor Item No_],
    pl.[Order Date],
    pil.[Posting Date],
    pil.[Expected Receipt Date],
    pih.[Notes] as [Header Notes],
    pil.[No_] as [G/L Account No],
    pih.[Buy-from Vendor No_],
    pih.[Buy-from Vendor Name],
    Pil.Quantity as [Inv Qty From InvoiceLine], 
    pil.[Amount Including VAT] as [Inv Value From InvoiceLine], 
    pl.Quantity as [PO Quantity From Purchaseline], 
    pl.[Quantity Received] as [Received Qty From PurchaseLine],
    pl.[Quantity Invoiced] as [Invoiced Qty From PurchaseLine] ,
    pl.[Amount Including VAT] as [PO Value From PurchaseLine]
FROM 
    [Purch_ Inv_ Line] pil
    INNER JOIN Purch_ Inv_ Header] pih
        ON pil.[Document No_] = pih.[No_]
    LEFT JOIN [Purchase Line] pl 
        ON pih.[PO Number]=pl.[Document No_] and pl.[Line No_]=pil.[Line No_]
WHERE 
    PIL.[Document No_] IN
    (
        SELECT distinct pil.[Document No_] FROM   
            Purch_ Inv_ Line] pil 
        WHERE piL.[No_] in ('700xxx','700xxx','17xxxxx') and pil.[Posting Date] >=getdate()-7
    )
    AND piL.[Type]='1'

1 个答案:

答案 0 :(得分:0)

获得NULL值可能有两个原因:

  • [购买行] 表格中的列值实际为NULL

  • 对于NULL的行, [购买行] 表中没有匹配的行。这就是LEFT JOIN的工作原理

如果您只想获得匹配的行,请将LEFT JOIN更改为INNER JOIN - 然而,您的结果集不会包含来自 [Purch_ Inv_ Line] 和<的行strong> [Purch_ Inv_ Header] ,其中 [购买行] 行不匹配。

如果您想将默认值设为NULL,可以使用ISNULL执行此操作:

ISNULL(pl.[Amount Including VAT], 0) as [PO Value From PurchaseLine]