Hello.
You could solve that problem by making two additional tables (temporary or not, depends on your requirements and SQL engine) which structure will be mapping the columns from query.
For example:
CREATE TABLE TableA (
Col1 int,
Col2 bit,
Col3 varchar(4),
Col4 varchar(4)
)
CREATE TABLE TableB (
Col1 int,
Col2 bit,
Col3 varchar(4),
Col4 varchar(4)
)
Note that this is only an example structure based on the output data which you have presented.
After making those two tables, you would have to insert data from query to each of the tables.
Added:
You don't have to execute the same query twice. Execute it once, put the data to the TableA then make SELECT on TableA and put data to the TableB. That will save you a lot of time.
The last step would be to perfrom query on TableA and TableB with JOIN on their columns Col3 and Col4. Something like this:
SELECT A.Col1, A.Col2, B.Col1, B.Col2, COALESCE(A.Col3, B.Col3), COALESCE(A.Col4, B.Col4)
FROM TableA A INNER JOIN TableB B ON A.Col3 = B.Col3 AND A.Col4 = B.Col4
Hope this will help.
Also please keep in mind that this solution has one major drawback:
If you change number of columns or their data type in the oryginal query, you will have to also update the table definitions.
Possible solution to this would be using a dynamic sql, but it is generally not adviced.
After edit (you've provided additional NULLS in output data):
If you want to keep NULL values, you should use different join, for example: LEFT OUTER JOIN
Another possible solutions are:
Just replace (SELECT * FROM dbo.Test) with your long query.
However this will cause that query will be run twice.
SELECT A. *, B. * FROM (SELECT * FROM dbo.Test) A LEFT OUTER JOIN (SELECT * FROM dbo.Test) B ON A.Col3 = B.Col3 AND A.Col4 = B.Col4 AND A.Col1 <> B.Col1 AND A.Col2 <> B.Col2
If you use SQL 2005 you could try to use CROSS APPLY operator.
There might be other solutions but you must be more descriptive about SQL engine that you use and your rights on the database.