PIVOT中的列不是所需的序列

时间:2013-04-17 17:29:12

标签: tsql pivot

我刚刚开始使用SQL PIVOT并且对列的排序存在问题,并且对如何纠正它很有帮助。我已经在这里和其他网站上筛选了几篇与PIVOT相关的帖子,但没有立即发生任何相关内容。

你会注意到我在每个查询中添加了一个硬编码的OrderBy文件,但这没有帮助,我认为这是pitot正在对列进行排序的[Description]字段。所以目前列按以下顺序从左到右显示:

[收费期],[优秀],[好],[临时编号],[满意],[不满意],[非常好] 。< / p>

相反,我需要以下顺序:

[收费期],[临时编号],[优秀],[非常好],[良好],[满意],[不满意]

我开始认为它可能不是一个纯粹的枢轴问题 - 从来没有我可以使用一些帮助,谢谢。

存储过程如下所示:

DECLARE @cols NVARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)

SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' + [Description] 
FROM dbo.vQualScoringGrade 
ORDER BY '],[' + [Description] FOR XML PATH('')), 1,2,'') + ']'

SET @query = N'SELECT [Fee Period], ' + @cols + ' FROM 
(SELECT [Award Fee Period],GradeCount, Description, Value, OrderBy FROM 
dbo.vQualScoringGrade) p
PIVOT (SUM([Value]) for [Description] IN ( ' + @cols + ' )) AS pvt ORDER BY [Fee Period]'

execute(@query)

提供sproc的视图[vQualScoringGrade]如下所示:

SELECT TOP (100) PERCENT [Fee Period], GradeCount, Description, 
GradeCount AS Value, OrderBy
FROM (SELECT [Fee Period], 'No of Interim' AS Description, COUNT(VerNumber) AS GradeCount, 1 AS
OrderBy
FROM dbo.vQualScoringExcellent AS vQualScoringExcellent
GROUP BY GIIANumber, Description
UNION
SELECT [Fee Period], 'Excellent' AS Description, COUNT(Description) AS GradeCount, 2 AS OrderBy
FROM dbo.vQualScoringExcellent AS vQualScoringExcellent_1
GROUP BY VerNumber, Description
UNION
SELECT [Fee Period], 'Very Good' AS Description, COUNT(Description) AS GradeCount, 3 AS OrderBy
FROM dbo.vQualScoringVeryGood AS vQualScoringVeryGood
GROUP BY VerNumber, Description
UNION
SELECT [Fee Period], 'Good' AS Description, COUNT(Description) AS GradeCount, 4 AS OrderBy
FROM dbo.vQualScoringGood AS vQualScoringGood
GROUP BY VerNumber, Description
UNION
SELECT [Fee Period], 'Satisfactory' AS Description, COUNT(Description) AS GradeCount, 5 AS
OrderBy
FROM dbo.vQualScoringSatisfactory AS vQualScoringSatisfactory
GROUP BY VerNumber, Description
UNION
SELECT [Fee Period], 'Unsatisfactory' AS Description, COUNT(Description) AS GradeCount, 6 AS OrderBy
FROM dbo.vQualScoringUnsatisfactory AS vQualScoringUnsatisfactory
GROUP BY VerNumber, Description) AS QualScoringGrade
ORDER BY OrderBy

2 个答案:

答案 0 :(得分:1)

试试这样:

SELECT @cols = STUFF((SELECT '],[' + [Description] 
    FROM dbo.vQualScoringGrade 
    GROUP BY [Description] 
    ORDER BY MAX([orderby]), [Description] 
    FOR XML PATH('')), 1,2,'') + ']'

答案 1 :(得分:0)

您在此处指定了按字母顺序排列的列:

SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' + [Description] 
  FROM dbo.vQualScoringGrade 
  ORDER BY '],[' + [Description] FOR XML PATH('')), 1,2,'') + ']'

添加ORDER BY子句。

如果每个描述都有一个关联的列顺序字段,您可以对其进行排序以获得明确的顺序。

除此之外:通常从查询返回的列的顺序并不重要。使用数据的应用程序负责格式化数据。该owuld包括以合适的顺序显示它。