--[C6martPeriodico].[PL_MP_S146RischioDiversificazione] 'S','CPPBRN41H45C773S'
CREATE procedure [C6MartPeriodico].[PL_MP_S146RischioDiversificazione]
-- Add the parameters for the stored procedure here
 @Rete char(1), 
 @CodiceFiscale varchar(16)
AS
BEGIN
	declare @contaCC as int
	select @contaCC = count(*)
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' and cod_fiscale = @codiceFiscale and rete = @rete
	declare @contaPOS as int
	select @contaPOS = count(*)
	from c6martperiodico.patrimonio_Bf
	where cod_fiscale = @codiceFiscale and rete = @rete
SELECT 
K.COD_FISCALE,
K.RETE,
CASE 
	WHEN (@contaPOS - @contacc = 0) THEN 0
	ELSE VAR_PERC_PTF 
END AS VAR,
CASE WHEN ISNULL(COPERTURA,0.00) = 0.00 AND @contaPOS - @contacc <> 0 THEN 'n.c.' ELSE NULL END as varString,
CASE 
	WHEN (ISNULL(copertura,100) < 100) AND @contaPOS - @contacc <> 0
		--THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
		THEN REPLACE(CAST(CAST(COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') --+ '%'  
	ELSE null 
END AS coperturaString,
beneficio as diversificazione,
CASE 
	WHEN (@contaPOS - @contacc = 0) THEN 100
	ELSE COPERTURA
END AS COPERTURA,
case 
when cod_Aggreg = 'COMPLESSIVO' then 'Patrimonio Complessivo'
when cod_Aggreg = 'COMPLESSIVO|BF' then 'Patrimonio ' + (case when k.rete ='F' then 'Fideuram' else 'Sanpaolo Invest' end)
when cod_Aggreg = 'COMPLESSIVO|TERZI' then 'Patrimonio altri Istituti'
ELSE ''
END AS PATRIMONIO,
case 
	when b.profilo is null then -1 
	else b.profilo
end as profiloCode,
b.max_var as var_profilo,
--V l'ordine serve per la corretta visualizzazione del report: Patrimonio casa, patrimonio terzi, patrimonio complessivo
--V Monitoraggio prende soltanto la prima riga, diagnosi anche nel caso non ci siano i terzi.
case 
when cod_Aggreg = 'COMPLESSIVO' then 3
when cod_Aggreg = 'COMPLESSIVO|BF' then 1
when cod_Aggreg = 'COMPLESSIVO|TERZI' then 2
ELSE ''
END AS Ordine
FROM
C6MARTperiodico.RISCHIO_AGGREGATO K left outer JOIN c6martperiodico.mifid a
	ON k.cod_fiscale = a.cod_fiscale and
		k.rete = a.rete
	left outer join
C6Martperiodico.CODIFICA_RISCHIO b on
A.PROFILO_ASS=B.PROFILO
WHERE
--A.PROFILO_ASS=B.PROFILO
--AND K.RETE=A.RETE
--AND K.COD_FISCALE= A.COD_FISCALE
COD_AGGREG IN ('COMPLESSIVO|BF', 'COMPLESSIVO', 'COMPLESSIVO|TERZI')
AND k.COD_FISCALE = @COdiceFISCALE
AND k.RETE= @RETE
ORDER BY 11
END