简体   繁体   English

SQL通过引用自行联接

[英]SQL Join on Self by Reference

I have a table called Form. 我有一个名为Form的表。 I have grossly simplified it as follows: 我已将其简化如下:

    FormID     Ref     Premium
    1          AA      1000
    1          BB      900
    1          CC      600
    1          DD      100
    2          AA      0
    2          BB      0
    2          CC      0
    7          AA      211
    7          BB      101
    7          CC      300

Let's say for example that FormID = 1 corresponds to 2013 data and FormID = 7 corresponds to 2012 data (prior year). 举例来说,FormID = 1对应于2013年数据,FormID = 7对应于2012年数据(前一年)。

I want the joined data such that I expect this table out: 我想要这样的联接数据:

    CurrentFormID PriorFormID Ref PremiumCurrent PremiumPrior
    1             7           AA      1000       211
    1             7           BB      900        101
    1             7           CC      600        300
    1             NULL (OR 7) DD      100        NULL (OR 0)

Essentially I need something similar to an outer join where I specify the CurrentFormID, PriorFormID as variables (ie. 1 and 7). 本质上,我需要类似于外部联接的东西,在其中我将CurrentFormID,PriorFormID指定为变量(即1和7)。 The references must be the same OR the reference in the old data must be null. 引用必须相同,或者旧数据中的引用必须为null。

This query below is a start, but I am only getting back the values that overlap (ie the References that are common in both sets. I need to also get entries where there is no reference match in the prior form. 下面的查询是一个开始,但是我只返回了重叠的值(即,两个集合中都通用的引用。我还需要获取先前形式中没有引用匹配的条目。

    SELECT 
        *
    FROM
        Form X
     OUTER JOIN Form Y
    ON  (X.FormID = @CurrentFormID AND Y.FormID = @PriorFormID) -
    WHERE X.Reference = Y.Reference
    ORDER BY X.Reference

I hope I have made sense. 我希望我有道理。

You should interchange the ON and WHERE clauses: 您应该互换ON和WHERE子句:

SELECT 
    *
FROM
    Form X
 OUTER JOIN Form Y
ON X.Reference = Y.Reference    
WHERE X.FormID = @CurrentFormID AND (Y.FormID IS NULL OR Y.FormID = @PriorFormID)

ORDER BY X.Reference
SELECT
    X.FormId AS CurrentFormId,
    Y.FormId AS PriorFormId,
    X.Ref,
    X.Premium AS CurrentPremium,
    Y.Premium AS PriorPremium
FROM
    #MyTable X
LEFT JOIN
    (SELECT * FROM #MyTable WHERE FormId <> @CurrentFormId) Y  
ON
    X.Ref = Y.Ref
WHERE
    X.FormId = @CurrentFormId AND (Y.FormId = @PriorFormId OR Y.FormId IS NULL)

Alternatively, the subquery can be built like this: 另外,子查询可以这样构建:

(SELECT * FROM #MyTable WHERE FormId = @PriorFormId) Y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM