Joining tables created by a look

  • Joining tables created by a LOOP!:hehe:

    I am trying created an output using a loop that look like this (the top row is column headers)

    Model State 1/1/2007

    40 Series AlaskaNULL

    40 Series Arizona08/01/2010

    60 Series Alabama01/01/2010

    60 Series Arizona01/01/2012

    80 Series Alabama01/01/2010

    80 Series AlaskaNULL

    80 Series ArizonaNULL

    There is an output for each month from 1/1/2007 to 12/1/2015 and I need them all in the same table so it looks like this:

    Model State 1/1/2007 2/1/2007 ..............

    40 Series AlaskaNULL Null

    40 Series Arizona08/01/2010 10/01/2010

    60 SeriesAlabama01/01/2010 NULL

    60 SeriesArizona01/01/2012 05/01/2010

    80 SeriesAlabama01/01/2010 NULL

    80 SeriesAlaskaNULL 09/01/2009

    80 SeriesArizonaNULL 02/01/2009

    The code I wrote to create the tables involved adding a certain number of months to each header column to find the dates in the output. I cannot use UNION since there is so much different output tables. Any suggestions?

  • amy_davis07 (3/16/2016)


    Joining tables created by a LOOP!:hehe:

    Since you are asking how to join the tables, I will just pretend not to have seen how you created them.

    (But just for the record, loops are almost always a bad idea in SQL Server)

    Any suggestions?

    Post the data you have as a script that we can run, e.g. CREATE TABLE and INSERT statements that will recreate the same situation in our test database. Limit the data to just a few rows of sample data that covers all cases that need to be covered.

    Post the *exact* expected result that you need based on the sample data provided, along with an explanation of the logic.

    (And since you mention that you need output for every month in a 9-year period, I suggest that you post a simplified version for, let's say, a four-month period).


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply