我正在通过在一张桌子上执行一系列计算并通过取消/转动来转置它来制作会计报告,以便它符合我想要的格式。
问题是当我将列展开到行中时,结果输出会按字母顺序自动对行进行排序。我想知道是否有办法阻止不要做这件事并将列的确切顺序转换成行。
这是我的动态pivot / unpivot的代码:
ALTER PROCEDURE dbo.GenerateFormattedFFOReport
AS
BEGIN
SET NOCOUNT ON;
DECLARE @COLSUNPIVOT AS NVARCHAR(MAX),
@QUERY AS NVARCHAR(MAX),
@COLSPIVOT AS NVARCHAR(MAX),
@COLSUNPIVOTORDER AS NVARCHAR(MAX)
SELECT @COLSUNPIVOT = STUFF((SELECT ','+QUOTENAME(C.NAME)
FROM SYS.COLUMNS C WITH(NOLOCK)
WHERE C.OBJECT_ID = OBJECT_ID('GenerateFFOReportData') AND C.NAME <> 'Quarter'
FOR XML PATH('')), 1, 1, '')
SELECT @COLSUNPIVOTORDER = STUFF
SELECT @COLSPIVOT = STUFF((SELECT ',' + QUOTENAME([Quarter])
FROM GenerateFFOReportData T FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')
SELECT @COLSUNPIVOT
SET @QUERY
= 'SELECT HEADER, '+@COLSPIVOT+'
FROM
(
SELECT HEADER,[Quarter],VALUE FROM GenerateFFOReportData
UNPIVOT
(
VALUE FOR HEADER IN ('+@COLSUNPIVOT+')
) UNPIV
) SRC
PIVOT
(
SUM(VALUE)
FOR [Quarter] IN ('+@COLSPIVOT+')
) PIV'
EXEC (@QUERY)
END
GO
感谢您提供任何帮助。