我有一组存储在数据库中的原始数据,如下所示:
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
我目前使用TSQL和动态SQL生成表格,因为可以通过日期选择器选择报告日期。我想让输出看起来如下:
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
这是我当前的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+']')
FROM AVTABLE WHERE ReportDate > getdate() - 22 GROUP BY ReportDate ORDER BY ReportDate
SET @query = 'SELECT Server,'+@cols2+' FROM AVTABLE AS SRC PIVOT (Min(AvgAvail) FOR ReportDate in ('+@cols+')) AS PVT'
EXEC(@query)
问题是Pivot正在复制带有中断号码的行。有关如何解决它的任何想法? TIA
答案 0 :(得分:1)
此查询将为您提供所需的结果。不使用数据透视语法。
DECLARE @cols NVARCHAR(2000) =''
DECLARE @cols2 NVARCHAR(2000)=''
DECLARE @query NVARCHAR(4000)=''
SELECT @cols = @cols + ',[OutageID] = MAX(CASE WHEN ReportDate = '''+CAST(ReportDate as varchar)+''' THEN OutageID END)'
+ ',['+CAST(ReportDate as varchar)+'] = MAX(CASE WHEN ReportDate ='''+CAST(ReportDate as varchar)+''' THEN avgavail END)'
FROM AVTABLE GROUP BY ReportDate ORDER BY ReportDate
SET @query = 'SELECT [server] ' +@cols+ ' FROM AVTABLE GROUP BY [server] '
EXECUTE (@query)