Duplicate Columns in TSQL Pivot -
i have set of raw data stored in database looks following:
reportdate server avgavail outageid 6/4/2015 cpu1 0.9797 11111111 6/4/2015 cpu2 0.9999 null 6/4/2015 cpu3 0.9999 null 6/4/2015 cpu4 0.9999 null 6/5/2015 cpu1 0.9999 null 6/5/2015 cpu2 0.9999 null 6/5/2015 cpu3 0.9887 22222222 6/5/2015 cpu4 0.9999 null 6/6/2015 cpu1 0.9999 null 6/6/2015 cpu2 0.9999 null 6/6/2015 cpu3 0.9999 null 6/6/2015 cpu4 0.9999 null 6/6/2015 cpu5 0.9999 null
i use tsql dynamic sql generate table because report dates can chosen via date picker. output following:
server outageid 6/4/2015 outageid 6/5/2015 outageid 6/6/2015 cpu1 11111111 0.9797 null 0.9999 null 0.9999 cpu2 null 0.9999 22222222 0.9887 null 0.9999 cpu3 null 0.9999 null 0.9999 null 0.9999 cpu4 null 0.9999 null 0.9999 null 0.9999 cpu5 null null null null null 0.9999
here current sql:
declare @cols nvarchar(2000) declare @cols2 nvarchar(2000) declare @query nvarchar(4000) select @cols = coalesce( @cols+',['+ reportdate +']','['+ reportdate+']'), @cols2 = coalesce( @cols2+',[outageid],['+ reportdate +']','[outageid],['+ reportdate+']') avtable reportdate > getdate() - 22 group reportdate order reportdate set @query = 'select server,'+@cols2+' avtable src pivot (min(avgavail) reportdate in ('+@cols+')) pvt' exec(@query)
problem pivot duplicating rows outage numbers. thoughts on how fix it? tia
this query give results want.does not use pivot syntax.
declare @cols nvarchar(2000) ='' declare @cols2 nvarchar(2000)='' declare @query nvarchar(4000)='' select @cols = @cols + ',[outageid] = max(case when reportdate = '''+cast(reportdate varchar)+''' outageid end)' + ',['+cast(reportdate varchar)+'] = max(case when reportdate ='''+cast(reportdate varchar)+''' avgavail end)' avtable group reportdate order reportdate set @query = 'select [server] ' +@cols+ ' avtable group [server] ' execute (@query)
Comments
Post a Comment