Search code examples
sqlsql-servercorrelated-subquery

Correlated subquery structured data formatting


Im starting out in SQL so be kind, I have created 7 query script that I can run to extract data. I have been told that rather than getting 7 independent files they want all of the data together in one report in a delimited format, so that the MAIN EOC prints one line and all the other queries print with that EOC record, then to the next EOC record as such:

TYPE RECORD ACCOUNT NUM  
EOC       1| 000001     | 1stuff | 1stuff |More 1stuff |More 1stuff | even more 1stuff
DIAG      2| 000001     | 2stuff | More 2stuff | even more 2stuff
DIAG      2| 000001     | 2stuff | More 2stuff | even more 2stuff
ADMIN     3| 000001     | 3stuff |More 3stuff | even more 3stuff
ADMIN     3| 000001     | 3stuff |More 3stuff | even more 3stuff
PROC      4| 000001     | 4stuff | 4stuff |More 4stuff | even more 4stuff
EVENTS    5| 000001     | 5stuff | 5stuff |More 5stuff | even more 5stuff
EVENTS    5| 000001     | 5stuff | 5stuff |More 5stuff | even more 5stuff
EOC       1| 000002     | 1stuff | 1stuff |More 1stuff |More 1stuff | even more 1stuff
DIAG      2| 000002     | 2stuff | More 2stuff | even more 2stuff
DIAG      2| 000002     | 2stuff | More 2stuff | even more 2stuff
ADMIN     3| 000002     | 3stuff |More 3stuff | even more 3stuff
ADMIN     3| 000002     | 3stuff |More 3stuff | even more 3stuff
PROC      4| 000002     | 4stuff | 4stuff |More 4stuff | even more 4stuff
EVENTS    5| 000002     | 5stuff | 5stuff |More 5stuff | even more 5stuff
EVENTS    5| 000002     | 5stuff | 5stuff |More 5stuff | even more 5stuff

etc ...........

You get the picture.

So how do I take the main EOC query, for example:

SELECT
    1Stuff
    ,More1Stuff
    ,EvenMore1Stuff
FROM Somewhere

And inject those new queries under each EOC row? I thought about it and realized I cant use a subquery as that will just add more data to the end of the EOC row. Anyone have any ideas on the matter.


Solution

  • Is this what you're looking for?

    select * from (
    <your query 1>
    union all
    <your query 2>
    union all
    <your query 3>
    ...
    union all
    <your query 7>
    )
    order by account num, record -- change the column names here