-- [C6martPeriodico].PL_MP_S142DistibuzionePerRating 'f','MSCLRT46H15A565B'
 CREATE procedure [C6MartPeriodico].[PL_MP_S142DistibuzionePerRating]
	@Rete char(1), 
	@CodiceFiscale varchar(16)
AS
BEGIN
	SET NOCOUNT ON;
SELECT 
	RATING,
	isnull(sum(T.CONTROVALORE),0) as CONTROVALORE ,
	isnull(sum(T.CONTROVALORE) / ((SELECT sum(BF.ctv)
								FROM c6MartPeriodico.ANAG_PRODOTTI ANAG
								INNER JOIN c6MartPeriodico.patrimonio_BF BF
								ON ANAG.COD_PRODOTTO = BF.COD_PRODOTTO
								AND BF.rete = @Rete
								AND BF.cod_fiscale = @CodiceFiscale
								AND ANAG.FLG_OB='S' )/100),0)  
	AS Percentage,
	CASE RATING
		WHEN 'Da AAA a A-' THEN 93
		WHEN 'Da BBB+ a BBB-' THEN 171
		WHEN 'Da BB+ a B-' THEN 174
		WHEN 'Da CCC+ a D' THEN 193
		ELSE 235
    END AS Red,
    CASE RATING
		WHEN 'Da AAA a A-' THEN 138
		WHEN 'Da BBB+ a BBB-' THEN 196
		WHEN 'Da BB+ a B-' THEN 135
		WHEN 'Da CCC+ a D' THEN 174
		ELSE 235 
    END AS Green,
    CASE RATING
		WHEN 'Da AAA a A-' THEN 153
		WHEN 'Da BBB+ a BBB-' THEN 150
		WHEN 'Da BB+ a B-' THEN 88
		WHEN 'Da CCC+ a D' THEN 149
		ELSE 236 
    END AS Blue
FROM (
		SELECT  
			CASE ANAG.rating 
				WHEN 'AAA' THEN 'Da AAA a A-'
				WHEN 'AA+' THEN 'Da AAA a A-'
				WHEN 'AA' THEN 'Da AAA a A-'
				WHEN 'AA-' THEN 'Da AAA a A-'
				WHEN 'A+' THEN 'Da AAA a A-'
				WHEN 'A' THEN 'Da AAA a A-'
				WHEN 'A-' THEN 'Da AAA a A-'
				WHEN 'BBB+' THEN 'Da BBB+ a BBB-'
				WHEN 'BBB' THEN 'Da BBB+ a BBB-'
				WHEN 'BBB-' THEN 'Da BBB+ a BBB-'
				WHEN 'BB+' THEN 'Da BB+ a B-'
				WHEN 'BB' THEN 'Da BB+ a B-'
				WHEN 'BB-' THEN 'Da BB+ a B-'
				WHEN 'B+' THEN 'Da BB+ a B-'
				WHEN 'B' THEN 'Da BB+ a B-'
				WHEN 'B-' THEN 'Da BB+ a B-'
				WHEN 'CCC+' THEN 'Da CCC+ a D'
				WHEN 'CCC' THEN 'Da CCC+ a D'
				WHEN 'CCC-' THEN 'Da CCC+ a D'
				WHEN 'CC' THEN 'Da CCC+ a D'
				WHEN 'C' THEN 'Da CCC+ a D'
				WHEN 'D' THEN 'Da CCC+ a D'
				ELSE 'Non classificato'
			END AS RATING,
			isnull(sum(BF.ctv),0) as CONTROVALORE 	
		FROM c6MartPeriodico.ANAG_PRODOTTI ANAG
				INNER JOIN c6MartPeriodico.patrimonio_BF BF
				ON ANAG.COD_PRODOTTO = BF.COD_PRODOTTO
				AND BF.rete = @Rete
				AND BF.cod_fiscale = @CodiceFiscale
				AND ANAG.FLG_OB='S' 
				GROUP BY  ANAG.rating
) T
GROUP BY  T.RATING 
ORDER BY T.RATING
END