简体   繁体   中英

SQL Join on Self by Reference

I have a table called 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).

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). The references must be the same OR the reference in the old data must be 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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