我目前正在开发这个脚本,作为一个支点,它为我提供了标准普尔评级的成熟度百分比。我的行总计如下:
;WITH CTE
AS
(
SELECT PortfolioID
, MaturityBand
, SandPRating
, MaturitySort
, (count(*)over(partition by PortfolioID,SandPRating,MaturityBand)*100.0) --/Test2)*100 As Pct
/
(
Select COUNT(*)
From @Worktable B
Where B.PortfolioID = A.PortfolioID
) As Pct
FROM @Worktable AS A
--WHERE SandPRating IS NOT NULL
UNION All
SELECT PortfolioID
, MaturityBand
, 'SandPRating_Total' AS SandPRating
, MaturitySort
, COUNT(*) * 100.0
/
(
Select COUNT(*)
From @Worktable AS B
Where B.PortfolioID = A.PortfolioID
) AS Total_Pct
FROM @Worktable AS A
--WHERE SandPRating IS NOT NULL
GROUP BY PortfolioID, MaturityBand, MaturitySort
)
, CTE2
AS
(
SELECT MaturityBand
, SandPRating
, MaturitySort
, PCT
FROM CTE
GROUP BY MaturityBand, SandPRating, MaturitySort, PCT
)
SELECT MaturityBand, [AAA],[AA+],[AA],[AA-],[A+],[A],[A-]
,[BBB+],[BBB],[BBB-],[BB+],[BB],[BB-],[B+],[B],[B-]
,[CCC+],[CCC],[CCC-],[CC],[C],[DDD],[DD],[D],[N.R.]
,[N.A.],[WR], [Unass], [SandPRating_Total]
FROM Cte2
PIVOT
(MAX(PCT)
FOR SandPRating
IN
(
[AAA],[AA+],[AA],[AA-],[A+],[A],[A-]
,[BBB+],[BBB],[BBB-],[BB+],[BB],[BB-],[B+],[B],[B-]
,[CCC+],[CCC],[CCC-],[CC],[C],[DDD],[DD],[D],[N.R.]
,[N.A.],[WR], [Unass], [SandPRating_Total])
) myPiv
ORDER BY MaturitySort
我的支点目前看起来像这样:
Maturity Band AAA AA A A- BBB+ BBB- BB+ BB Total
Less Than 1 yr 2.63% 5% 2% 9.63%
1 to 5 yrs 5% 5% 10%
5 to 10 yrs 5.00% 5% 10%
10 to 20 yrs 2% 2%
More than 20 yrs 10% 6% 1% 17%
我想要的是这样的:
Maturity Band AAA AA A A- BBB+ BBB- BB+ BB Total
Less Than 1 yr 2.63% 5% 2% 9.63%
1 to 5 yrs 5% 5% 10%
5 to 10 yrs 5.00% 5% 10%
10 to 20 yrs 2% 2%
More than 20 yrs 10% 6% 1% 17%
Total 17.63 5% 5% 2% 7% 5% 6% 1% 48.63%
但是我想添加列总计,有人可以帮忙吗?