有点令人费解,但在这里:
基本上,我的目标是生成一个动态查询,其中一列将标识值(A 列上的第一个值,B 列上的第二个值等),最后是一个包含总数的列。
之后,我们可以使用 cube 进行分组,这将对按不同列分组的值的所有排列求和。查看示例
最终结果将显示如下:
Total A B C D E
285.62 NULL NULL NA NA NA
这将表明 285.62 是第一个和第二个值的总和,按值排序
DECLARE @columns varchar(max) = ''
DECLARE @allcolumns varchar(max) = ''
DECLARE @columnName varchar(1) = 'A'
DECLARE @select varchar(max) = ''
SELECT
@columns = @columns + ',''NA'' AS ' + @columnName,
@allcolumns = @allcolumns + ',' + @columnName,
@columnName = CHAR(ASCII(@columnName)+1)
FROM
#mytemptable
SET @columnName = 'A'
SELECT
@select = @select + CHAR(13) + 'UNION SELECT ' + CONVERT(varchar(100),totals) + ' AS totals' + STUFF(@columns,2+10*(ord-1),4,'''' + @columnName + ''''), @columnName = CHAR(ASCII(@columnName)+1)
FROM
(SELECT totals, ROW_NUMBER() OVER(ORDER BY totals) ord from #mytemptable)
A
SET @select = STUFF(@select,1,6,'')
SET @allcolumns = STUFF(@allcolumns, 1,1,'')
--PRINT (@select)
EXEC ( 'SELECT * FROM (
SELECT SUM(totals) AS Total, ' + @allcolumns + '
FROM (' + @select + ') A GROUP BY ' + @allcolumns + ' WITH CUBE
) sub WHERE Total = 285.62 ')