• tshad (8/23/2012)


    Actually, it isn't exactly the same way.

    I was trying to figure out how to get your way to work with a middle table and couldn't get it to work.

    You're way works but it is different.

    In the query you have the CROSS JOIN in the Derived Table (df)

    SELECT *

    FROM (SELECT DealerID, DealerCode, DealerName, ForecastId, Name

    FROM Dealers d

    CROSS JOIN Forecast f) df

    LEFT OUTER JOIN DealerForecastMap m

    ON df.ForecastId = m.ForecastId AND df.DealerID = m.DealerID;

    In the old query, you have the CROSS JOIN outside of the Derived table (m).

    SELECT *

    FROM

    (SELECT DealerCode FROM Sales GROUP BY DealerCode) m

    CROSS JOIN Forecast fc

    LEFT JOIN [Sales] s

    on s.DealerCode = m.DealerCode AND s.ForecastID = fc.ForecastId

    ORDER BY m.DealerCode

    I am not sure of the difference but I do know I could not seem to get my query with the middle table to work as it was set up for my other example that had just 2 tables.

    Not sure why yet, but will look at it more closely.

    Thanks,

    Tom

    Hi Tom

    In both queries the intent is to build an intermediate table which is a cross of DealerID and ForecastID, to which you can LEFT JOIN other tables. This ensures that you're starting with the whole picture - every dealer has every forecast.

    The structural difference between the two queries is to accommodate the changes in the sample tables and data you've provided.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden