sql - Merge multiple records for the same foreign key -
the source pivoted table stored proc. know column names first 3 columns, remainder user defined pivot , don't know names ahead of time. here's example:
create table table1 ([id] int, [reportid] int, [fieldid] int, [col1] varchar(3), [col2] int, [col3] varchar(3)); insert 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 group data reportid, replacing null values non-null values when exist in other rows of same reportid. id column product of pivot , unused. fieldid column relates rest of columns.
(1, 2, 1, 'abc', 123, a3a) (4, 3, 1, 'def', 456, null) i looked @ using cursor worried scaling.
i looked @ using merge, don't know column names, cannot write columnname in place.
we have access text list of user defined column names querying table.
any ideas?
you can create dynamic sql using sys.columns system view follows
create table table1 ([id] int, [reportid] int, [fieldid] int, [col1] varchar(3), [col2] int, [col3] varchar(3)); insert 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); declare @sql varchar(max)='select min(id) id, reportid, min(fieldid) fieldid ' select @sql+=',min('+c.name+') '+c.name sys.columns c object_id=object_id(n'table1') , c.name not in ('id','reportid','fieldid') select @sql+=' table1 group reportid' exec (@sql) drop table table1 but in case may need grant select permission on sys.columns in master database.
i think, better group data in query table created.
Comments
Post a Comment