如何在保持列的原始顺序的同时动态地取消/转动?

时间:2015-03-06 20:24:16

标签: sql-server pivot unpivot

我正在通过在一张桌子上执行一系列计算并通过取消/转动来转置它来制作会计报告,以便它符合我想要的格式。

问题是当我将列展开到行中时,结果输出会按字母顺序自动对行进行排序。我想知道是否有办法阻止不要做这件事并将列的确切顺序转换成行。

这是我的动态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  

感谢您提供任何帮助。

0 个答案:

没有答案