Pivoting string fields in SQL Server 2008 R2 -
i need create dataset based on 1 generated series of sql sub-queries. results of sub-queries can replicated using following code:
create table table1 (`stayid` varchar(3), `incidentorder` int, `txdetails` varchar(73)) ; insert table1 (`stayid`, `incidentorder`, `txdetails`) values ('ip1', 1, 'ward: a9999 - 01/01/2015 - 15:23'), ('ip1', 2, 'consultant: joe bloggs specialty :geriatric medicine - 02/01/2015 - 08:17'), ('ip1', 3, 'discharge - 06/02/2015 - 16:40'), ('ip2', 1, 'consultant: joe bloggs - 01/01/2015 - 09:02'), ('ip2', 2, 'consultant: joe bloggs specialty :geriatric medicine - 02/01/2015 - 12:56'), ('ip2', 3, 'ward: a9999 - 02/01/2015 - 19:39'), ('ip2', 4, 'consultant: joe bloggs - 05/01/2015 - 08:22'), ('ip3', 1, 'ward: a9999 - 02/01/2015 - 04:58'), ('ip3', 2, 'consultant: joe bloggs specialty :gastroenterology - 02/01/2015 - 07:27'), ('ip3', 3, 'consultant: joe bloggs - 05/01/2015 - 09:06'), ('ip3', 4, 'ward: a9999 consultant: joe bloggs - 05/01/2015 - 16:45'), ('ip3', 5, 'ward: a9999 consultant: joe bloggs - 05/01/2015 - 17:10'), ('ip3', 6, 'ward: a9999 - 05/01/2015 - 18:14') ;
i need produce results follows:
columns: stayid, tx1, tx2, tx3, tx., txn
with transferdetails being populated each matching stayid , txn column (based on incidentorder).
the incidentorder not fixed , 10, 30, or 1 each stayid in data set, static pivot not option.
i have tried (and failed) producing required output using pivot , hopeful here can help.
thanks in advance
check dynamic query,
declare @colname varchar(max), @qry varchar(max) select @colname = isnull(@colname + ',','') + quotename(incidentorder) (select distinct incidentorder table1) cols set @qry = 'select stayid, ' + @colname + ' ( select stayid, incidentorder, txdetails table1 ) tbl pivot ( max(txdetails) incidentorder in (' + @colname + ') ) pvt' exec(@qry)
see fiddle here fiddle
Comments
Post a Comment