私は現在、S&P レーティングによる成熟度バンドのパーセンテージを提供するピボットのために、このスクリプトを現在開発中です。行の総計は次のとおりです。
;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%
ただし、列の総計を追加したいのですが、誰か助けてもらえますか?