The source is a pivoted table from a stored proc. We know the column names for the first three columns, but the remainder are user defined from the pivot and we don't know the names ahead of time. Here's an example:
CREATE TABLE Table1
([ID] int, [ReportID] int, [FieldID] int, [Col1] varchar(3), [Col2] int, [Col3] varchar(3));
INSERT INTO Table1
([ID], [ReportID], [FieldID], [Col1], [Col2], [Col3])
VALUES
(1, 2, 1, 'abc', NULL, NULL),
(2, 2, 2, NULL, 123, NULL),
(3, 2, 3, NULL, NULL, 'A3A')
(4, 3, 1, NULL, NULL, NULL),
(5, 3, 2, NULL, 456, NULL),
(6, 3, 3, 'def', NULL, NULL);
The desired output is to group the data by ReportID, replacing NULL values with non-NULL values when they exist in other rows of the same ReportID. The ID column is a product of the pivot and is unused. The FieldID column relates to the rest of the columns.
(1, 2, 1, 'abc', 123, A3A)
(4, 3, 1, 'def', 456, NULL)
I looked at using a cursor but worried about it scaling.
I looked at using MERGE, but don't know the column names, so cannot write it with the columnname in place.
We do have access to a text list of the user defined column names by querying another table.
Any ideas?