Left Outer Join on Select Top 1结果为Nulls

时间:2017-09-25 17:01:03

标签: sql tsql select join

当我使用以下代码加入最近更新的地址时,会导致ZIP中的所有关联字段返回为NULL。我已经尝试了外部应用程序并且它做得更好,但它并不能从正确的两个表中检索每个单独的zip,即使它们存在。

SELECT 
    i.ion_ID as [ION],
    zip.City as [City], 
    zip.StateCode as [State], 
    zip.ZipCode as [Zip Code], 
    zip.County as [County]
FROM     
    HWSP_t_ION i
        LEFT OUTER JOIN (SELECT TOP 1 ad.AssociatedIDValue, z.Zipcode, z.City, z.StateCode, z.County
                                    FROM CADD_t_Address ad
                                        LEFT OUTER JOIN CADD_lt_ZipCode z
                                            ON ad.zip = z.ZipCode
                                    ORDER BY ad.ChangedOn desc
                                        ) AS ZIP
        ON  zip.AssociatedIDValue = i.ION_ID

编辑: 这就是Outer Apply的样子:

SELECT 
    i.ion_ID as [ION],
    zip.City as [City], 
    zip.StateCode as [State], 
    zip.ZipCode as [Zip Code], 
    zip.County as [County]
OUTER APPLY                         (SELECT TOP 1 ad.zip
                                    FROM CADD_t_Address ad
                                    WHERE  ad.AssociatedIDValue = ci.ION_ID
                                    and [ad].[Status] = 'ACTIVE'
                                    ORDER BY ad.ChangedOn desc
                                        ) ad


OUTER APPLY                         (SELECT TOP 1 zip.Zipcode, zip.City, zip.StateCode, zip.County as [County]
                                    FROM CADD_lt_ZipCode zip
                                    WHERE ad.zip = zip.ZipCode
                                    ) zip

1 个答案:

答案 0 :(得分:1)

使用SQL时,请考虑您的数据集。想想您希望这些集合如何组合。在这种情况下,您只需要一行内部集合来获取外部集合的数据。窗口函数对于内部集合非常有效。你正在生成一个行号(rn)来指定排序中的第一行,然后消除任何不是rn = 1的行。一旦你有了这个最近的单一记录,那么只需链接这两组。

尝试类似:

SELECT 
    t1.ID
    , s2.blah
    , s2.moreBlah
FROM t1
LEFT OUTER JOIN (
    SELECT *
    FROM (
        SELECT t2.id, t2.blah, t3.moreBlah
            , ROW_NUMBER() OVER ( PARTITION BY <columnToBaseOrderFrom> ORDER BY changeDate DESC ) AS rn
        FROM t2
        LEFT OUTER JOIN t3 ON t2.refID = t3.id
    ) s1
    WHERE rn = 1
) s2 ON t1.id2 = s2.id

如果您需要消除NULL记录,则必须确定是否希望在没有来自s2子查询的匹配时删除t1中的行。如果是这种情况,你需要INNER JOIN而不是LEFT OUTER JOIN。