尝试透视数据并添加计算列无济于事。
我已经尝试了下面的封闭代码,但无法确切获得我想要的。
我的表格由三列组成
TABLE_NAME,REPORT_DATE,COUNT_ROWS
对于最后两个[REPORT_DATE],我试图显示每个[TABLE_NAME]的[COUNT_ROWS]
我想念什么?另外,我将如何添加一列以减去数据透视图中两个日期之间的值?
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(REPORT_DATE) + ',' FROM (select DISTINCT TOP 2 REPORT_DATE from account_report order by REPORT_DATE desc) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end
set @query =
'SELECT * from
(select [TABLE_NAME], [COUNT_ROWS] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [TABLE_NAME] in (' + @cols + ')
) piv'
execute(@query)
我从脚本中获得的是两个[REPORT_DATE]的两列结果,其中1行显示空值(尽管我的数据中确实包含行)
答案 0 :(得分:0)
我敢打赌,您正在尝试从查询中获取以下信息:
SELECT * from
(select [TABLE_NAME], [COUNT_ROWS], [REPORT_DATE] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [REPORT_DATE] in (' + @cols + ')
) piv
相反,如果您确实希望报表名称按列推出,则需要调整@cols
变量。
SELECT @cols = @cols + QUOTENAME(TABLE_NAME) + ',' FROM (select DISTINCT TOP 2 TABLE_NAME ,REPORT_DATE from account_report order by REPORT_DATE desc) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end
set @query =
'SELECT * from
(select [REPORT_DATE], [TABLE_NAME], [COUNT_ROWS] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [TABLE_NAME] in (' + @cols + ')
) piv'
execute(@query)