枢轴问题(我错过了啥)?
Posted
技术标签:
【中文标题】枢轴问题(我错过了啥)?【英文标题】:Pivoting Issue (what am I missing)?枢轴问题(我错过了什么)? 【发布时间】:2019-10-08 16:08:35 【问题描述】:尝试透视数据并添加计算列无济于事。
我已经尝试了下面随附的代码,但无法完全得到我想要的。
我的表格由三列组成
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 行显示空值(尽管我的数据确实包含行)
【问题讨论】:
【参考方案1】:我敢打赌,您正试图从查询中得到以下信息:
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)
【讨论】:
以上是关于枢轴问题(我错过了啥)?的主要内容,如果未能解决你的问题,请参考以下文章