0

我刚开始使用SQL PIVOT并且对列的排序有疑问,并且很想知道如何纠正它。我在这里和其他网站上筛选了几个与 PIVOT 相关的帖子,但没有任何内容立即引起人们的注意。

您会注意到我在每个查询中添加了一个硬编码的 OrderBy 文件,但这并没有帮助,我认为皮托管正在对列进行排序的是 [Description] 字段。因此,目前这些列按以下顺序从左到右出现:

[收费期]、[优秀]、[良好]、[中期]、[满意]、[不满意]、[很好]

相反,我需要以下顺序:

[收费期]、[临时数量]、[优秀]、[很好]、[良好]、[满意]、[不满意]

我开始认为这可能不是一个纯粹的支点问题 - 我可以使用一些帮助,谢谢。

存储过程如下所示:

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
4

2 回答 2

1

试试这样:

SELECT @cols = STUFF((SELECT '],[' + [Description] 
    FROM dbo.vQualScoringGrade 
    GROUP BY [Description] 
    ORDER BY MAX([orderby]), [Description] 
    FOR XML PATH('')), 1,2,'') + ']'
于 2013-04-17T19:09:48.730 回答
0

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

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

通过添加一个ORDER BY子句。

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

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

于 2013-04-17T17:38:17.287 回答