我有一个带有数据字段成为列的数据透视表的存储过程。目前返回的数据有一些冗余,想看看是否有办法纠正这个问题。存储过程实际上是在提供.rdlc
报告,当前输出如下所示:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
12 1
18 1
18 1
18 1
19 1
19 1
2 1
2 1
这就是它需要的样子:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
2 1 1
12 1
18 1 1 1
19 1 1
周期列需要按升序排序,并且需要将重复实例添加到同一行。
负责输出的存储过程和对应的视图如下:
BEGIN
DECLARE @cols NVARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SELECT @cols = STUFF((SELECT '],[' + [Description]
FROM vQualScoringGrade
GROUP BY [Description]
ORDER BY MAX([orderby]), [Description]
FOR XML PATH('')), 1,2,'') + ']'
SET @query = N'SELECT Period, ' + @cols + ' FROM
(SELECT Period, Description, Value, OrderBy FROM
vQualScoringGrade) p
PIVOT (SUM([Value]) for [Description] IN ( ' + @cols + ' )) AS pvt ORDER BY Period'
execute(@query)
end
SELECT TOP (100) PERCENT Period, Description, GradeCount AS Value, OrderBy
FROM (SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'NoOfInterim' AS Description, COUNT(Number) AS
GradeCount, 1 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Excellent' AS Description, COUNT(Description) AS
GradeCount, 2 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent_1
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'VeryGood' AS Description, COUNT(Description) AS
GradeCount, 3 AS OrderBy
FROM vQualScoringVeryGood AS vQualScoringVeryGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Good' AS Description, COUNT(Description) AS
GradeCount, 4 AS OrderBy
FROM vQualScoringGood AS vQualScoringGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Satisfactory' AS Description, COUNT(Description) AS
GradeCount, 5 AS OrderBy
FROM vQualScoringSatisfactory AS vQualScoringSatisfactory
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Unsatisfactory' AS Description, COUNT(Description) AS
GradeCount, 6 AS OrderBy
FROM vQualScoringUnsatisfactory AS vQualScoringUnsatisfactory
GROUP BY Number, Description) AS QualScoringGrade
ORDER BY OrderBy