﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE procedure [wh].[MERGED_PROCEDURE_20170615]
AS
BEGIN
	SET NOCOUNT ON;
---------------------------------------------------------------------
truncate table wh.pl_s85rendimentoportafogliocono
truncate table wh.pl_areemonitorate
truncate table wh.pl_s43lineaselfbf
truncate table wh.pl_s10patrimoniofinanziario
truncate table wh.pl_prodotti_non_associati_area_inv
truncate table wh.pl_d2_s151profilodirischio
truncate table wh.pl_d2_s152patrimonio
truncate table wh.pl_d2_s153patrimoniofinanziario
truncate table wh.pl_d2_s154patrimoniofinanziario
truncate table wh.pl_d2_s155patrimonioimmobiliare
truncate table wh.pl_d2_s156altropatrimonio
truncate table wh.pl_d2_s157confrontopiramidi
truncate table wh.pl_d2_s158piramidemodello
truncate table wh.pl_d2_s159patrimoniofinanziario
truncate table wh.pl_d2_s160dettaglioprodottibf
truncate table wh.pl_d2_s162dettaglioprodotti
truncate table wh.pl_d2_s163patrimoniofinanziariomassetclass
truncate table wh.pl_d2_s164polizzealtriistituti
truncate table wh.pl_d2_s165fondialtriistituti
truncate table wh.pl_d2_s167distribuzionerischiocredito
truncate table wh.pl_d2_s168tabellaemittenti
truncate table wh.pl_s43dettaglioprodottibf
truncate table wh.pl_d2_s169rischiomercatorischiocredito
truncate table wh.pl_d2_s170rischiodiversificazione
truncate table wh.pl_d2_s171patrimoniononrappresentabileassettclass
truncate table wh.pl_mp_s137bonus
truncate table wh.pl_mp_s135monitoraggioinvestimento
truncate table wh.pl_mp_s134monitoraggioliquidita
truncate table wh.pl_mp_s134bismonitoraggioliqinv
truncate table wh.pl_mp_s133bisprincipaliprodotti
truncate table wh.pl_mp_s133areebisognoprincprod
truncate table wh.pl_mp_s146rischiodiversificazione
truncate table wh.pl_mp_s141analisirisparmiotable
truncate table wh.pl_mp_s140analisirisparmiocharts
truncate table wh.pl_mp_s137biscapitaleprotetto
truncate table wh.pl_s43contocorrentebf
truncate table wh.pl_s43bisdettaglioprodottibf
truncate table wh.pl_s88patrimoniononconsideratonelcalcolodelrendimento
truncate table wh.pl_s82datisintetici
truncate table wh.pl_s82bisdatisintetici
truncate table wh.pl_s76alternativapatrimoniononrappresentabileassettclass
truncate table wh.pl_s80alternativa
truncate table wh.pl_s96rischiomercatorischiocredito
truncate table wh.pl_d_s170rischiodiversificazione
------------------------------------------------------------------------
-------------------------------------------PL_S82DatiSintetici
INSERT INTO WH.PL_S82DatiSintetici
SELECT 'C6MartPeriodico.PL_S82DatiSintetici' as ProcedureName, PATRAREA.RETE as i_rete ,PATRAREA.COD_FISCALE as i_codiceFiscale,	
		PATRAREA.ID_AREA AS need_area,
		ISNULL(RISCHIOAREA.VAR_PERC_PTF,0) AS var_needarea,
		CASE 
			WHEN RISCHIOAREA.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISCHIOAREA.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS var_needareaString,
		ISNULL(RISCHIOAREA.COPERTURA,0) AS copertura_needarea,
		CASE 
			WHEN RISCHIOAREA.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISCHIOAREA.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS copertura_needareaString,
		PATRAREA.ORDINAMENTO_PROGETTO,
		/*V Calcolato a livello di codice
		CASE
			WHEN PATRAGGR.CTV = 0 THEN 0
			ELSE PATRAREA.CTV / PATRAGGR.CTV * 100
		END AS pesoPerc,*/
		PATRAREA.CTV AS ControvaloreAttuale
		/* Calcolato a livello di codice
		CASE
			WHEN @TOTRischio = 0 THEN 0
			ELSE ISNULL(RISCHIOAREA.VAR_PERC_PTF,0) * PATRAREA.CTV / @TOTRischio * 100
		END AS rischioRelativo*/
	FROM C6MartPeriodico.vPatrimonioBFAggregatoPerArea AS PATRAREA
	INNER JOIN C6MartPeriodico.vPatrimonioBFAggregato AS PATRAGGR
		ON PATRAGGR.RETE = PATRAREA.Rete
		AND PATRAGGR.COD_FISCALE = PATRAREA.COD_FISCALE
	LEFT OUTER JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIOAREA
		ON RISCHIOAREA.COD_AGGREG = 'RISFIN|PIRAMIDE|' + LEFT(PATRAREA.ID_AREA,3)
		AND RISCHIOAREA.RETE = PATRAREA.Rete
		AND RISCHIOAREA.COD_FISCALE = PATRAREA.COD_FISCALE
	WHERE 1=1
			AND PATRAREA.ID_AREA IN ('RIS','EXT','LIQ','PRE')
-------------------------------------------------------------------------
-------------------------------------------PL_S85RendimentoPortafoglioCono
	BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
SELECT
       [RETE]
      ,[COD_FISCALE]
      ,[ID_AREA]
      ,isnull([NOME_PROGETTO],'XXX') as NOME_PROGETTO
      ,[TIPO_PROGETTO]
      ,[PERC_AREA]
      ,[CTV_PROGETTO]
      ,[CTV_AREA]
      ,[ORIZZ_TEMP_NUM]
      ,[ORIZZ_TEMP]
      ,[CTV_TOTALE]
      ,[STATO_CONSULENZA]
      ,[DATA_STATO_CONS]
      ,[DATA_MIGR_CONS]
      ,[ID_CONTRATTO]
      ,[ORDINAMENTO_PROGETTO]
      ,[ID_ELAB]
      ,[TIPO_ELAB]
into #pir_mod_xxx
  FROM [C6MartPeriodico].[PIRAMIDE_MOD]
--select * from #pir_mod_xxx where cod_fiscale = 'FF@7181'
INSERT INTO WH.PL_S85RendimentoPortafoglioCono
SELECT 'C6MartPeriodico.PL_S85RendimentoPortafoglioCono' as ProcedureName, CONO.RETE as i_rete ,CONO.COD_FISCALE as i_codiceFiscale,
		CONO.ID_AREA AS NEED_AREA,
		CASE
			WHEN CONO.NOME_PROGETTO = 'XXX' THEN ''
			ELSE CONO.NOME_PROGETTO
		END AS NOME_PROGETTO,
		cono.ordinamento_progetto,
		CONO.DATA_CONO,
		CONO.SCENARIO_OTTIMISTICO AS OTTIMISTICO,
		CONO.SCENARIO_PESSIMISTICO AS PESSIMISTICO,
		isnull(PIRMOD.ORIZZ_TEMP_NUM,0) * 12 AS ORIZZONTE_MESI,
		MONIT.RENDIMENTO_CUMULATO AS RENDIMENTO,
		MONIT.DATA_CTV AS DATA_MONIT
	FROM
		C6MartPeriodico.CONO_PIANIFICAZIONE AS CONO
	INNER JOIN C6MartPeriodico.MONITORAGGIO_ATTUALE AS MONIT
		ON CONO.RETE = MONIT.RETE
		AND CONO.COD_FISCALE = MONIT.COD_FISCALE
		AND CONO.ID_AREA = MONIT.ID_AREA
		AND CONO.NOME_PROGETTO = MONIT.NOME_PROGETTO
		And cono.ordinamento_progetto=monit.ordinamento_progetto --l'ordinamento progetto è sempre pari alla chiaveprogetto e non idmonitoraggio
	INNER JOIN #pir_mod_xxx as PIRMOD
		ON CONO.RETE = PIRMOD.RETE
		AND CONO.COD_FISCALE = PIRMOD.COD_FISCALE
		AND CONO.ID_AREA = PIRMOD.ID_AREA
		AND CONO.NOME_PROGETTO = PIRMOD.NOME_PROGETTO
		And cono.ordinamento_progetto=pirmod.ordinamento_progetto
--	INNER JOIN C6MartPeriodico.PIRAMIDE_MOD AS PIRMOD
--		ON CONO.RETE = PIRMOD.RETE
--		AND CONO.COD_FISCALE = PIRMOD.COD_FISCALE
--		AND CONO.ID_AREA = PIRMOD.ID_AREA
--		AND CONO.NOME_PROGETTO = PIRMOD.NOME_PROGETTO
	ORDER BY CONO.DATA_CONO
	drop table #pir_mod_xxx
END
-------------------------------------------------------------------------
-------------------------------------------pl_areemonitorate
BEGIN
INSERT INTO WH.PL_AreeMonitorate
SELECT 'C6MartPeriodico.PL_AreeMonitorate' as ProcedureName, [RETE] as i_rete ,[COD_FISCALE] as i_codiceFiscale, 
NEED_AREA,
NEED_ESTESA,
max(NOME_PROGETTO) as NOME_PROGETTO,
--CONTROLLO NOME PROGETTO DUPLICATO, TOLTO IL MAX, AGGIUNTO NEL GROUP BY
ISNULL(ORDINAMENTO_PROGETTO,-1111),
--MAX(ORDINAMENTO_PROGETTO) AS ORDINAMENTO_PROGETTO,
MAX(ORDINE) AS ORDINE,
--rimettere il min e commentare il ctv=0
max(AREAPROGETTOSOTTOMONITORAGGIO) AS AREAPROGETTOSOTTOMONITORAGGIO
FROM
(
	--1.1 liq sotto monit
	SELECT
	    PIRMOD.RETE AS RETE,
		PIRMOD.COD_FISCALE as COD_FISCALE,
		PIRMOD.ID_AREA AS Need_Area,		
		AREA.NOME_AREA AS Need_Estesa,
		CASE WHEN PIRMOD.NOME_PROGETTO is null and pirmod.id_area='Inv' THEN 'Prodotti non associati a progetti'		
			ELSE LTRIM(RTRIM(PIRMOD.NOME_PROGETTO))
		END AS Nome_Progetto,
		PIRMOD.ORDINAMENTO_PROGETTO as ORDINAMENTO_PROGETTO,
	 CASE PIRMOD.ID_AREA 
		 WHEN 'Liq' THEN 1
		 WHEN 'Ris' THEN 2
		 WHEN 'Pre' THEN 3
		 WHEN 'Inv' THEN 4		 
		 WHEN 'Ext' THEN 5
		 WHEN 'Na' THEN 6
	END AS ORDINE,
    CASE WHEN MONIT.COD_FISCALE IS NULL THEN 0 ELSE 1 END AS AREAPROGETTOSOTTOMONITORAGGIO 
	FROM
		(SELECT 
		RETE,
		COD_FISCALE,
		case when ID_AREA in ('Pre','Pre1','Pre2') then 'Pre' else id_area end as  Id_area,
		NOME_PROGETTO,
		TIPO_PROGETTO,
		PERC_AREA,
		CTV_PROGETTO,
		CTV_AREA,
		ORIZZ_TEMP_NUM,
		ORIZZ_TEMP,
		CTV_TOTALE,
		STATO_CONSULENZA,
		DATA_STATO_CONS,
		DATA_MIGR_CONS,
		DATA_PIANIF,
		ID_CONTRATTO,   ---LEVARE???
        ORDINAMENTO_PROGETTO
	FROM
        C6MartPeriodico.CONS_ATTIVAGGIORNATA	
        ) PIRMOD
		INNER JOIN C6MartPeriodico.AREA_BISOGNO AS AREA ON
			PIRMOD.ID_AREA = AREA.ID_AREA
        LEFT OUTER JOIN C6MARTPERIODICO.MONITORAGGIO_ATTUALE MONIT
        ON MONIT.COD_FISCALE=PIRMOD.COD_FISCALE
        AND MONIT.RETE=PIRMOD.RETE
        AND MONIT.ID_AREA= PIRMOD.ID_AREA 
        AND MONIT.NOME_PROGETTO= ISNULL(PIRMOD.NOME_PROGETTO,'XXX')
		AND MONIT.ORDINAMENTO_PROGETTO=PIRMOD.ORDINAMENTO_PROGETTO
	WHERE
		PIRMOD.CTV_PROGETTO > 0
		AND PIRMOD.ID_AREA NOT IN ('Pre1', 'Pre2', 'Cc')
 --V ordine cambiato da 5 a 6 inquanto 5 è lo stesso di ext, na è passato a 7
 --Bido Added for 'SN' Saldo Negativo
	  UNION	
	  SELECT DISTINCT
	  PATRBF.RETE AS RETE,
	  PATRBF.COD_FISCALE as COD_FISCALE,
	  'Cc' AS Need_Area,
	  'Conti correnti a saldo negativo'AS Need_Estesa,
	  NULL AS Nome_Progetto,
	  --999999 as ORDINAMENTO_PROGETTO,
      ORDINAMENTO_PROGETTO as ORDINAMENTO_PROGETTO,
      6 AS ORDINE,
      0 as AREAPROGETTOSOTTOMONITORAGGIO 
	  FROM
      C6MARTPERIODICO.PATRIMONIO_BF PATRBF
      WHERE 
	  PATRBF.CTV < 0 and id_area = 'CC'
-- End Of Bido Added for 'SN' Saldo Negativo
  	  UNION	
	  SELECT DISTINCT
	  PATRBF.RETE AS RETE,
	  PATRBF.COD_FISCALE as COD_FISCALE,
	  'Self' AS Need_Area,
	   'Liquidità negativa "Linee GP Eligo"' AS Need_Estesa,
	  NULL AS Nome_Progetto,
	  --999999 as ORDINAMENTO_PROGETTO,
      ORDINAMENTO_PROGETTO as ORDINAMENTO_PROGETTO,
      7 AS ORDINE,
      0 as AREAPROGETTOSOTTOMONITORAGGIO 
	  FROM
      C6MARTPERIODICO.PATRIMONIO_BF PATRBF
      WHERE 
	  PATRBF.CTV < 0 and id_area = 'SELF'
-- End Of Bido Added for 'SN' Saldo Negativo
    UNION 
    SELECT DISTINCT
	    PATRBF.RETE AS RETE,
	    PATRBF.COD_FISCALE as COD_FISCALE,
		'Na' AS Need_Area,
		'Non allocato'AS Need_Estesa,
		NULL AS Nome_Progetto,
		--999999 as ORDINAMENTO_PROGETTO,
        ORDINAMENTO_PROGETTO as ORDINAMENTO_PROGETTO,
        8 AS ORDINE,
        0 as AREAPROGETTOSOTTOMONITORAGGIO 
	  FROM
      C6MARTPERIODICO.PATRIMONIO_BF PATRBF
      WHERE 
		PATRBF.CTV > 0
		AND PATRBF.ID_AREA  IN ('Na')
      UNION 
         SELECT DISTINCT
		PATRBF.RETE AS RETE,
	    PATRBF.COD_FISCALE as COD_FISCALE,
		case when PATRBF.ID_AREA in ('Pre','Pre1','Pre2') then 'Pre' else PATRBF.ID_AREA end  AS Need_Area,
		case when PATRBF.ID_AREA in ('Pre','Pre1','Pre2') then 'Previdenza' else AREA.NOME_AREA end as NEED_ESTESA ,
		CASE WHEN PATRBF.NOME_PROGETTO is null and PATRBF.id_area='Inv' THEN 'Prodotti non associati a progetti'		
		ELSE PATRBF.NOME_PROGETTO end AS Nome_Progetto,
		--case when PATRBF.ID_AREA in ('Pre','Pre1','Pre2') then 1 else  PATRBF.ORDINAMENTO_PROGETTO end  as ORDINAMENTO_PROGETTO,
		PATRBF.ORDINAMENTO_PROGETTO  as ORDINAMENTO_PROGETTO,
        CASE PATRBF.ID_AREA 
		 WHEN 'Liq' THEN 1
		 WHEN 'Ris' THEN 2
		 WHEN 'Pre' THEN 3
         WHEN 'Pre1' THEN 3
         WHEN 'Pre2' THEN 3
		 WHEN 'Inv' THEN 4		 
		 WHEN 'Ext' THEN 5
		 WHEN 'Na' THEN 7
	END AS ORDINE,
       CASE WHEN MONIT.COD_FISCALE IS NULL THEN 0 ELSE 1 END AS AREAPROGETTOSOTTOMONITORAGGIO 
	  FROM
      C6MARTPERIODICO.PATRIMONIO_BF PATRBF 
	  INNER JOIN C6MartPeriodico.AREA_BISOGNO AS AREA ON
	  PATRBF.ID_AREA = AREA.ID_AREA
      LEFT OUTER JOIN C6MARTPERIODICO.MONITORAGGIO_ATTUALE MONIT
        ON MONIT.COD_FISCALE=PATRBF.COD_FISCALE
        AND MONIT.RETE=PATRBF.RETE
        AND MONIT.ID_AREA= PATRBF.ID_AREA 
        AND MONIT.NOME_PROGETTO= ISNULL(PATRBF.NOME_PROGETTO,'XXX')
		AND MONIT.ORDINAMENTO_PROGETTO=PATRBF.ORDINAMENTO_PROGETTO
       WHERE
        1=1 
		AND PATRBF.CTV > 0
        AND PATRBF.EXTRANAC=1
		AND PATRBF.ID_AREA  NOT IN ('Na', 'Cc') 
) A
GROUP BY
RETE,
COD_FISCALE,
NEED_AREA,
NEED_ESTESA,
ISNULL(ORDINAMENTO_PROGETTO,-1111)
	ORDER BY
		ORDINE
END
-------------------------------------------------------------------------
-------------------------------------------PL_S43LineaSelfBF
BEGIN
	INSERT INTO WH.PL_S43LineaSelfBF
	SELECT 'C6MartPeriodico.PL_S43LineaSelfBF' as ProcedureName, LS.rete as i_rete ,LS.codfis as i_codiceFiscale, 	  	 	 
		 codconf as NumContratto,
		 isnull(ctv,0) as Controvalore,
--INIZIO Intervento Eligo Titoli		 
		 NomeProdotto as NomeProdotto,
--FINE   Intervento Eligo Titoli		 		 
		 dbo.ToShortDateString(cast(datasott as varchar))  as DataSott
	FROM       
		C6MartPeriodico.ANAG_SELF LS	
	WHERE 
		isnull(ctv,0) < 0
END
-------------------------------------------------------------------------
-------------------------------------------PL_S10PatrimonioFinanziario
BEGIN
	INSERT INTO WH.PL_S10PatrimonioFinanziario
	SELECT 'C6MartPeriodico.PL_S10PatrimonioFinanziario' as ProcedureName, [Rete] as i_rete ,[CodiceFiscale] as i_codiceFiscale, 	
       [Banca]
      ,[Ordinamento]
      ,[AssetClassId]
      ,[AssetClassName]
      ,[Controvalore]
      ,[Percentuale]
      ,[Totale]
  FROM [C6MartPeriodico].[tb_S10PatrimonioFinanziario]
  order by ordinamento
END 
-------------------------------------------------------------------------
-------------------------------------------PL_Prodotti_Non_Associati_Area_Inv
BEGIN
INSERT INTO WH.PL_Prodotti_Non_Associati_Area_Inv
	SELECT 'C6MartPeriodico.PL_Prodotti_Non_Associati_Area_Inv' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale,
PATRBF.RETE,
PATRBF.COD_FISCALE,
ISNULL(PATRBF.NOME_PROGETTO,'Prodotti non associati a progetti') AS NOME_PROGETTO,
ID_AREA as NEED_AREA,
SUM(CTV) AS CONTROVALOREATTUALE,
MAX(ISNULL(RISK.VAR_PERC_PTF,0)) AS var_needarea,
--PATRBF.ORDINAMENTO_PROGETTO as ORDINAMENTO_PROGETTO,
PATRBF.CHIAVE_PROGETTO as ORDINAMENTO_PROGETTO,
		CASE 
			WHEN RISK.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISK.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS var_needareaString
FROM
C6MARTPERIODICO.PATRIMONIO_BF  PATRBF
LEFT OUTER JOIN 
C6MARTPERIODICO.RISCHIO_AGGREGATO RISK 
ON PATRBF.RETE = RISK.RETE
			AND PATRBF.COD_FISCALE = RISK.COD_FISCALE
			AND RISK.COD_AGGREG = 'PIRAMIDE|Inv|'+ ISNULL(PATRBF.NOME_PROGETTO,'Prodotti non associati a progetti')
WHERE 1 = 1	
    AND PATRBF.id_AREA = 'Inv' 
    AND PATRBF.NOME_PROGETTO='Prodotti non associati a progetti'        
GROUP BY 
PATRBF.RETE,
PATRBF.COD_FISCALE,
ISNULL(PATRBF.NOME_PROGETTO,'Prodotti non associati a progetti'),
ID_AREA,
CHIAVE_PROGETTO,
		CASE 
			WHEN RISK.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISK.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END 
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S151ProfiloDiRischio
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @varBF DECIMAL(12,2)
	DECLARE @coperturaBF DECIMAL(12,2)
	INSERT INTO WH.PL_D2_S151ProfiloDiRischio
	SELECT 'C6MartPeriodico.PL_D2_S151ProfiloDiRischio' as ProcedureName, M.RETE as i_rete, M.COD_FISCALE as i_codiceFiscale,
        M.PROFILO_ASS as codiceProfilo,
		DBO.TOSHORTDATESTRING(M.DATA_INIZIO_VAL) as dataInizioValidita,
		CR.MAX_VAR as varMassimo,
		ISNULL(@varBF,0) as varBF,
		ISNULL(@coperturaBF,0) as coperturaBF,
		ProfiliDiRischio.NOMEPROFILO  as nomeProfilo,
        m.riskclass as riskclass,
        m.experience as experince
	FROM	
		C6MartPERIODICO.MIFID AS M
		INNER JOIN C6MartPERIODICO.CODIFICA_RISCHIO AS CR
		ON M.PROFILO_ASS = CR.PROFILO
		INNER JOIN DBO.ProfiliDiRischio AS ProfiliDiRischio
		ON M.PROFILO_ASS = ProfiliDiRischio.CODICEPROFILO
END
-------------------------------------------------------------------------
-------------------------------------------pl_d2_s152patrimonio
BEGIN
SELECT SUM(CTV) as Value, patrBF.Rete,  patrBF.Cod_Fiscale
into #PatrimonioBF
             FROM C6MartPeriodico.PATRIMONIO_BF patrBF
             WHERE patrBF.id_area not in ('CC','SELF')  
             group by patrBF.Cod_Fiscale, patrBF.Rete
       SELECT SUM(IMPORTO) as Value, Rete, Cod_Fiscale
       into #Part_viaggianti 
             FROM
             (
                           SELECT SUM(IMPORTO) AS IMPORTO, partvia.Rete, partvia.Cod_Fiscale
                                 FROM C6Martperiodico.PARTITE_VIAGGIANTI partvia
                                        group by partvia.Rete, partvia.Cod_Fiscale
                           union 
                           SELECT SUM(PARTVIA_DISINV) AS IMPORTO, partvia.Rete, partvia.Cod_Fiscale
                                 FROM C6Martperiodico.patrimonio_bf partvia
                                        group by partvia.Rete, partvia.Cod_Fiscale
             ) T
             group by  Rete, Cod_Fiscale
    SELECT SUM(ROUND(CTV,2)) as Value, patrTerzi.Rete,
                    patrTerzi.Cod_Fiscale
                    into #PatrimonioTerzi
             FROM C6MartPeriodico.PATRIMONIO_TERZI patrTerzi
             group by patrTerzi.Rete,
                    patrTerzi.Cod_Fiscale
       SELECT SUM(patrImm.VALORE_STIMATO) as Value,
       patrImm.Rete, patrImm.Cod_Fiscale
       into #PatrimonioImmobiliare
             FROM C6MartPeriodico.PATRIMONIO_IMMOBILIARE patrImm
             group by patrImm.Rete, patrImm.Cod_Fiscale
       SELECT SUM(patrAltro.ctv) as Value, patrAltro.Rete, patrAltro.Cod_Fiscale
       into #PatrimonioAltro
             FROM C6MartPeriodico.PATRIMONIO_ALTRO patrAltro
             group by patrAltro.Rete, patrAltro.Cod_Fiscale
             select distinct rete, cod_fiscale
             into #merge
             from
             (
                    select rete, cod_fiscale from #PatrimonioBF UNION ALL
                    select rete, cod_fiscale from #PatrimonioTerzi UNION ALL
                    select rete, cod_fiscale from #Part_viaggianti  UNION ALL
                    select rete, cod_fiscale from #PatrimonioImmobiliare UNION ALL
                    select rete, cod_fiscale from  #PatrimonioAltro
             )x
			 truncate table WH.pl_d2_s152patrimonio	
             ;with data as
             (
             select m.rete, m.cod_fiscale, 
                    cast(COALESCE(a.value,0.00)+COALESCE(c.value,0.00) as numeric(18,2)) as PatrimonioBF,
                    cast(COALESCE(a.value,0.00)+COALESCE(b.value,0.00)+COALESCE(c.value,0.00) as numeric(18,2)) as FinanziarioCTV,
                    cast(COALESCE(a.value,0.00)+COALESCE(b.value,0.00)+COALESCE(c.value,0.00)+COALESCE(d.value,0.00)+COALESCE(e.value,0.00) as numeric(18,2)) as PatrimonioTotale,
                    cast(COALESCE(b.value,0.00) as numeric(18,2)) as PatrimonioTerziCTV,
                    cast(COALESCE(d.value,0.00) as numeric(18,2)) as PatrimonioImmobiliare,
                    cast(COALESCE(e.value,0.00) as numeric(18,2)) as PatrimonioAltro
             from #merge m
                    left join #PatrimonioBF a                  on a.rete = m.rete and a.cod_fiscale = m.cod_fiscale
                    left join #PatrimonioTerzi b               on b.rete = m.rete and b.cod_fiscale = m.cod_fiscale
                    left join #Part_viaggianti c               on c.rete = m.rete and c.cod_fiscale = m.cod_fiscale
                    left join #PatrimonioImmobiliare d         on d.rete = m.rete and d.cod_fiscale = m.cod_fiscale
                    left join #PatrimonioAltro e           on e.rete = m.rete and e.cod_fiscale = m.cod_fiscale
                    )
		INSERT INTO WH.pl_d2_s152patrimonio		
	    SELECT  'C6MartPeriodico.pl_d2_s152patrimonio' as ProcedureName, rete as i_rete, cod_fiscale as i_codiceFiscale,
                    PatrimonioBF, 
                    PatrimonioTerziCTV,
                    FinanziarioCTV,
                    CONVERT(decimal(6,2),
                           case when PatrimonioTotale = 0.00 then 0.00 
                           else FinanziarioCTV / PatrimonioTotale end 
                    * 100.00) AS FinanziarioPerc,
                    PatrimonioImmobiliare,
                    CONVERT(decimal(6,2),
                           case  when PatrimonioTotale = 0.00 then 0.00 
                           else PatrimonioImmobiliare/PatrimonioTotale end 
                    * 100.00) AS ImmobiliarePerc,
                    PatrimonioAltro,
                    CONVERT(decimal(6,2),
                           case PatrimonioTotale when 0.00 then 0.00 
                           else PatrimonioAltro/PatrimonioTotale end
                    * 100.00) AS AltroPerc,
                    PatrimonioTotale as TotaleCTV
                    from data
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S153PatrimonioFinanziario
BEGIN
	INSERT INTO WH.PL_D2_S153PatrimonioFinanziario
	SELECT 'C6MartPeriodico.PL_D2_S151ProfiloDiRischio' as ProcedureName, Rete as i_rete, Cod_Fiscale as i_codiceFiscale, 
		Intermediario,
		Ordine,
		Banca,
		Controvalore,
		round(Percentuale,2) as Percentuale
	FROM 
	(
		SELECT DISTINCT
		    Rete,
			Cod_Fiscale,
			Intermediario,
			Ordine,
			CASE Rete WHEN 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' END AS Banca,			 
			SUM(ctv) over (partition by Intermediario,Ordine,Rete,Cod_fiscale) AS CONTROVALORE,
			(
				(SUM(ctv) over (partition by Intermediario,Ordine,Rete,Cod_Fiscale)) / 
				wh.IsZero((SUM(ctv) over (partition by 'Totale'+Rete+Cod_fiscale)),1)
			 ) * 100 AS PERCENTUALE
		FROM 
		(
			SELECT 
			    patrBF.Rete as Rete,
				patrBF.Cod_Fiscale as Cod_Fiscale,
				CASE patrBF.Rete WHEN 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' END AS Intermediario,
				SUM(ROUND(CTV,2)) AS ctv,
				1 AS ordine
				FROM C6MartPeriodico.PATRIMONIO_BF patrBF
				WHERE 1 = 1				
					and patrBF.id_area  not in ('CC','SELF')
				GROUP BY patrBF.Rete, patrBF.Cod_Fiscale
			UNION ALL
			SELECT 
			    patrTerzi.Rete as Rete,
				patrTerzi.Cod_Fiscale as Cod_Fiscale,
				Intermediario, 
				SUM(ROUND(CTV,2)) AS ctv,
				2 AS ordine
				FROM C6MartPeriodico.PATRIMONIO_TERZI patrTerzi
				WHERE 1 = 1
				GROUP BY patrTerzi.Intermediario, patrTerzi.Rete, patrTerzi.Cod_Fiscale
		) PATR
		GROUP BY Cod_Fiscale, Rete, intermediario, ordine, ctv
	) A
	WHERE CONTROVALORE IS NOT NULL
	ORDER BY Ordine
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S154PatrimonioFinanziario
BEGIN
INSERT INTO WH.PL_D2_S154PatrimonioFinanziario
	SELECT 'C6MartPeriodico.PL_D2_S154PatrimonioFinanziario' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale, 
	A.Banca,
	A.Ordinamento,
	A.AssetClassId, 
	A.AssetClassName, 
	cast(A.Controvalore as decimal(38,6)) Controvalore,
	A.Percentuale,
	cast(ROUND(SUM(A.Controvalore) OVER (PARTITION BY 'TOTALE'+RETE+COD_FISCALE),2) as decimal(38,6)) AS PatrimonioFinanziarioCTV
FROM 
(		
	SELECT DISTINCT
		RETE,
		COD_FISCALE,
		CASE RETE WHEN 'S' THEN 'Sanpaolo Invest'ELSE 'Fideuram' END AS Banca,
		ASSETCLASS.ORDINAMENTO AS Ordinamento,
		VALORIASSET.ID_ASSETCLASS AS AssetClassId, 
		ASSETCLASS.DESCRIZIONE AS AssetClassName, 
		SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS+RETE+COD_FISCALE) AS Controvalore,
		(
			SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS+RETE+COD_FISCALE) /
			NULLIF(SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE'+RETE+COD_FISCALE),0)
		) * 100 AS Percentuale
	FROM (
		SELECT 	--PRODOTTI BF ESCLUSI GLI ASUL
			PATRBF.RETE AS RETE,
			PATRBF.COD_FISCALE as COD_FISCALE,
			ASSETPERC.ID_ASSETCLASS,
			PATRBF.CTV*ASSETPERC.PERC as Controvalore
		FROM C6MartPeriodico.PATRIMONIO_BF PATRBF
		INNER JOIN C6MartPeriodico.ASSET_PERC ASSETPERC 
			ON PATRBF.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
			AND ASSETPERC.LIVELLO = 1
		WHERE 
			PATRBF.TIPO_PRODOTTO NOT IN ('ASUL') 
			AND PATRBF.ID_AREA  not in ('CC','SELF') 
		UNION ALL
		SELECT 
			ASUL.RETE AS RETE,
			ASUL.COD_FISCALE as COD_FISCALE,
			ASSETPERC.ID_ASSETCLASS,
			ASUL.CTV*ASSETPERC.PERC as Controvalore
		FROM 
			C6MartPeriodico.DETTAGLIO_ASUL ASUL
		INNER JOIN 
			C6MartPeriodico.ASSET_PERC ASSETPERC
			ON 
				ASSETPERC.COD_PRODOTTO = ASUL.COD_PRODOTTO
				---ELIMINO GLI SKANDIA
				AND ASUL.COD_ISIN_SOTT = ''
				AND ASSETPERC.LIVELLO = 1
		UNION ALL
		--CON SKANDIA
		SELECT 
				ASUL.RETE AS RETE,
				ASUL.COD_FISCALE as COD_FISCALE,
				ASSETPERC.ID_ASSETCLASS,
				ASUL.CTV*ASSETPERC.PERC as Controvalore
		FROM C6MartPeriodico.DETTAGLIO_ASUL ASUL
		INNER JOIN C6MartPeriodico.ASSET_PERC ASSETPERC
			--PRENDO SOLO GLI SKANDIA
			ON ASSETPERC.COD_ISIN = ASUL.COD_ISIN_SOTT
			AND ASSETPERC.COD_MAF = ASUL.COD_MAF_SOTT
			AND ASSETPERC.COD_INTERNO = ASUL.COD_INTERNO
            AND rtrim(ASSETPERC.COD_SOTTOPRODOTTO) = ASUL.COD_SOTTOPRODOTTO
			AND ASSETPERC.LIVELLO = 1
		UNION ALL
		--PRODOTTI TERZI A CATALOGO
		SELECT
		    PATRTERZI.RETE AS RETE,
			PATRTERZI.COD_FISCALE as COD_FISCALE,
			ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') ID_ASSETCLASS,
			PATRTERZI.CTV*ISNULL(ASSETPERC.PERC,1) as Controvalore
		FROM 
			C6MartPeriodico.PATRIMONIO_TERZI PATRTERZI
		LEFT OUTER JOIN 
			C6MartPeriodico.ASSET_PERC ASSETPERC 
			ON 
				PATRTERZI.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
				AND ASSETPERC.LIVELLO = 1
		WHERE 1 = 1
			AND PATRTERZI.COD_PRODOTTO <> 'PRODOTTO NON IN CATALOGO'
		UNION ALL
		--PRODOTTI TERZI NON A CATALOGO
		SELECT 	
			PATRTERZI.RETE AS RETE,
			PATRTERZI.COD_FISCALE as COD_FISCALE,
			ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') ID_ASSETCLASS,
			PATRTERZI.CTV*ISNULL(ASSETPERC.PERC,1) as Controvalore
		FROM 
			C6MartPeriodico.PATRIMONIO_TERZI PATRTERZI
		LEFT OUTER JOIN 
			C6MartPeriodico.ASSET_PERC_TERZI ASSETPERC 
			ON 
				PATRTERZI.COD_PRODOTTO_TERZI = ASSETPERC.COD_PRODOTTO_TERZI
				AND ASSETPERC.LIVELLO = 1
		WHERE 1 = 1
			AND PATRTERZI.COD_PRODOTTO = 'PRODOTTO NON IN CATALOGO'
	) VALORIASSET
	INNER JOIN 
		C6MartPeriodico.ASSETCLASS ASSETCLASS
		ON 
			ASSETCLASS.ID_ASSETCLASS = VALORIASSET.ID_ASSETCLASS
	--GROUP BY RETE, COD_FISCALE, ASSETCLASS.ordinamento, VALORIASSET.ID_ASSETCLASS, ASSETCLASS.DESCRIZIONE, VALORIASSET.CONTROVALORE
) A
--GROUP BY RETE, COD_FISCALE, A.BANCA, A.ORDINAMENTO, A.ASSETCLASSID, A.ASSETCLASSNAME, A.CONTROVALORE, A.PERCENTUALE
ORDER BY A.ORDINAMENTO
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S155PatrimonioImmobiliare
BEGIN
INSERT INTO WH.PL_D2_S155PatrimonioImmobiliare
	SELECT 'C6MartPeriodico.PL_D2_S155PatrimonioImmobiliare' as ProcedureName, PATRIMONIO_IMMOBILIARE.RETE as i_rete, PATRIMONIO_IMMOBILIARE.COD_FISCALE as i_codiceFiscale,	
			PATRIMONIO_IMMOBILIARE.DESCRIZIONE AS Descrizione,
			PATRIMONIO_IMMOBILIARE.TIPOLOGIA AS Tipologia,
			PATRIMONIO_IMMOBILIARE.LOCALITA AS Localita,
			isnull(PATRIMONIO_IMMOBILIARE.AFFITTO,0) AS AffittoPercepito,
			PATRIMONIO_IMMOBILIARE.valore_stimato AS Valore,
			SUM(PATRIMONIO_IMMOBILIARE.VALORE_STIMATO) OVER (PARTITION BY 'Totale'+PATRIMONIO_IMMOBILIARE.RETE+PATRIMONIO_IMMOBILIARE.COD_FISCALE) as Totale,
			SUM(isnull(PATRIMONIO_IMMOBILIARE.AFFITTO,0)) OVER (PARTITION BY 'TotaleAffitto'+PATRIMONIO_IMMOBILIARE.RETE+PATRIMONIO_IMMOBILIARE.COD_FISCALE) as TotaleAffitto
	FROM C6MARTperiodico.PATRIMONIO_IMMOBILIARE 
	--GROUP BY PATRIMONIO_IMMOBILIARE.RETE, PATRIMONIO_IMMOBILIARE.COD_FISCALE, PATRIMONIO_IMMOBILIARE.descrizione, PATRIMONIO_IMMOBILIARE.TIPOLOGIA, PATRIMONIO_IMMOBILIARE.LOCALITA, PATRIMONIO_IMMOBILIARE.AFFITTO, PATRIMONIO_IMMOBILIARE.VALORE_STIMATO
	ORDER BY PATRIMONIO_IMMOBILIARE.valore_stimato DESC
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S156ALtroPatrimonio
BEGIN
	INSERT INTO WH.PL_D2_S156ALtroPatrimonio
	SELECT 'C6MartPeriodico.PL_D2_S156ALtroPatrimonio' as ProcedureName, PATRIMONIO_ALTRO.RETE as i_rete, PATRIMONIO_ALTRO.COD_FISCALE as i_codiceFiscale,	
		PATRIMONIO_ALTRO.DESCRIZIONE AS Denominazione,
		PATRIMONIO_ALTRO.QUANTITA AS NumeroQuote,
		PATRIMONIO_ALTRO.CTV AS Valore,
		SUM(PATRIMONIO_ALTRO.CTV) OVER (PARTITION BY 'Totale',PATRIMONIO_ALTRO.RETE, PATRIMONIO_ALTRO.COD_FISCALE ) as Totale
	FROM 
		C6MartPeriodico.PATRIMONIO_ALTRO 
		--GROUP BY PATRIMONIO_ALTRO.RETE, PATRIMONIO_ALTRO.COD_FISCALE, PATRIMONIO_ALTRO.DESCRIZIONE, PATRIMONIO_ALTRO.QUANTITA, PATRIMONIO_ALTRO.CTV 
	ORDER BY 
		PATRIMONIO_ALTRO.CTV DESC
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S157ConfrontoPiramidi
BEGIN
INSERT INTO WH.PL_D2_S157ConfrontoPiramidi
SELECT 'C6MartPeriodico.PL_D2_S157ConfrontoPiramidi' as ProcedureName, RETE as i_rete, [CodiceFiscale] as i_codiceFiscale,	
	 [NeedArea]
      ,[AreaName]
      ,[PercentualeModello]
      ,[PercentualeAttuale]
      ,[ControvaloreAttuale]
      ,[ControvaloreModello]
      ,[Totale_Percentuale]
      ,[DifferenzaEuro]
      ,[DifferenzaPercentuale]
      ,[var_needarea]
      ,[var_needareaString]
      ,[copertura_needarea]
      ,[copertura_needareaString]
      ,[Nota]
      ,[somma_controvalAttuale]
      ,[somma_controvalModello]
      ,[somma_percentualeAttuale]
      ,[somma_percentualeModello]
      ,[var_tot]
      ,[var_totString]
      ,[var_tot_pir]
      ,[var_tot_pirString]
      ,[copertura_tot]
      ,[copertura_totString]
      ,[copertura_tot_pir]
      ,[copertura_tot_pirString]
      ,[VAR_RISFIN]
      ,[VAR_RISFINSTRING]
      ,[copertura_risfin]
      ,[copertura_risfinString]
      ,[ordinamento]
  FROM [C6MartPeriodico].[TB_S133_S157DatiPiramide]
  where [CodiceFiscale] is not null and [Rete] is not null
  order by ordinamento
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S158PiramideModello
BEGIN
INSERT INTO WH.PL_D2_S158PiramideModello
SELECT 'C6MartPeriodico.PL_D2_S158PiramideModello' as ProcedureName, BF.RETE as i_rete, BF.COD_FISCALE as i_codiceFiscale,	
		  BF.NOME_PROGETTO AS NomePrg,
			   PIRMOD.ORIZZ_TEMP AS OrizzTempPrg,
			   AGGR.VAR_PERC_PTF as VarPrg,
			   SUM(BF.CTV)AS ControvalorePrg
		FROM  C6MartPeriodico.PATRIMONIO_BF BF 
		INNER JOIN C6MartPeriodico.RISCHIO_AGGREGATO AGGR
			ON BF.RETE= AGGR.RETE
			AND BF.COD_FISCALE= AGGR.COD_FISCALE
			AND AGGR.COD_AGGREG = 'RISFIN|PIRAMIDE|' + LEFT(BF.ID_AREA,3) + '|' + BF.NOME_PROGETTO
		INNER JOIN C6MartPeriodico.PIRAMIDE_MOD PIRMOD
			ON BF.RETE= PIRMOD.RETE
			AND BF.COD_FISCALE= PIRMOD.COD_FISCALE
			AND BF.ID_AREA = PIRMOD.ID_AREA
			AND BF.NOME_PROGETTO = PIRMOD.NOME_PROGETTO
		WHERE 1=1
		AND BF.ID_AREA = 'inv'
		AND BF.CTV > 0
		group BY BF.NOME_PROGETTO,PIRMOD.ORIZZ_TEMP,AGGR.VAR_PERC_PTF, BF.RETE, BF.COD_FISCALE
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S159PatrimonioFinanziario
BEGIN
INSERT INTO WH.PL_D2_S159PatrimonioFinanziario
SELECT 'C6MartPeriodico.PL_D2_S159PatrimonioFinanziario' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale,
	A.BANCA AS Banca,
	A.ORDINAMENTO AS Ordinamento,
	A.AssetClassId AS AssetClassId, 
	A.AssetClassName AS AssetClassName, 
	cast(A.Controvalore as decimal(38,6)) AS Controvalore,
	cast(A.Percentuale  as decimal(38,6)) AS Percentuale,
	cast(ROUND(SUM(A.Controvalore) OVER (PARTITION BY 'TOTALE'+RETE+COD_FISCALE),2)  as decimal(38,6))  AS Totale
FROM 
(		
	SELECT DISTINCT
		RETE,
		COD_FISCALE,
		CASE RETE
			WHEN 'S' THEN 'Sanpaolo Invest'
			ELSE 'Fideuram' 
		END AS Banca,
		ASSETCLASS.ORDINAMENTO,
		VALORIASSET.ID_ASSETCLASS AS AssetClassId, 
		ASSETCLASS.DESCRIZIONE AS AssetClassName, 
		ROUND(SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS+RETE+COD_FISCALE),2) as Controvalore,
		(
			SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS+RETE+COD_FISCALE) /
            --16.07.2011 COLAIANNI CONSOLI GESTIONE DIVISIONE PER ZERO
			CASE WHEN ( SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE'+RETE+COD_FISCALE) ) = 0 
				 THEN 1 
                 ELSE ( SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE'+RETE+COD_FISCALE) ) 
            END  
		) * 100 AS Percentuale
	FROM (
		SELECT 	
			PATRBF.RETE AS RETE,
			PATRBF.COD_FISCALE AS COD_FISCALE,
			ASSETPERC.ID_ASSETCLASS,
			PATRBF.CTV*ASSETPERC.PERC as Controvalore
		FROM 
			C6MartPeriodico.PATRIMONIO_BF PATRBF
		INNER JOIN 
			C6MartPeriodico.ASSET_PERC ASSETPERC 
			ON 
				PATRBF.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
				AND ASSETPERC.LIVELLO = 1
		WHERE 
			--ELIMINO I CONTRATTI ASUL PERCHE' UTILIZZIAMO IL DETTGALIO CHE PRENDIAMO CON LA SECONDA QUERY
			(PATRBF.TIPO_PRODOTTO NOT IN ('ASUL'))--,'CC'))
			and patrbf.id_area not in ('CC','Self')
		UNION ALL
		SELECT 
			ASUL.RETE AS RETE,
			ASUL.COD_FISCALE AS COD_FISCALE,
			ASSETPERC.ID_ASSETCLASS,
			ASUL.CTV*ASSETPERC.PERC as Controvalore
		FROM 
			C6MartPeriodico.DETTAGLIO_ASUL ASUL
		INNER JOIN 
			C6MartPeriodico.ASSET_PERC ASSETPERC
			ON 
				ASSETPERC.COD_PRODOTTO = ASUL.COD_PRODOTTO
				---ELIMINO GLI SKANDIA
				AND ASUL.COD_ISIN_SOTT = ''
				AND ASSETPERC.LIVELLO = 1
		UNION ALL
		SELECT  ASUL.RETE AS RETE,
				ASUL.COD_FISCALE AS COD_FISCALE,
				ASSETPERC.ID_ASSETCLASS,
				ASUL.CTV*ASSETPERC.PERC as Controvalore				
		FROM C6MartPeriodico.DETTAGLIO_ASUL ASUL
		INNER JOIN C6MartPeriodico.ASSET_PERC ASSETPERC
			--PRENDO SOLO GLI SKANDIA
			ON ASSETPERC.COD_ISIN = ASUL.COD_ISIN_SOTT
			AND ASSETPERC.COD_MAF = ASUL.COD_MAF_SOTT
			AND ASSETPERC.COD_INTERNO = ASUL.COD_INTERNO
            AND rtrim(ASSETPERC.COD_SOTTOPRODOTTO) = ASUL.COD_SOTTOPRODOTTO
			AND ASSETPERC.LIVELLO = 1
	) VALORIASSET
	INNER JOIN 
		C6MartPeriodico.ASSETCLASS ASSETCLASS
		ON 
			ASSETCLASS.ID_ASSETCLASS = VALORIASSET.ID_ASSETCLASS
) A
--group by RETE, COD_FISCALE, a.banca, a.ordinamento, a.assetclassid, a.assetclassname, a.controvalore, a.percentuale
ORDER BY A.ORDINAMENTO
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S160DettaglioProdottiBF
BEGIN
INSERT INTO WH.PL_D2_S160DettaglioProdottiBF
SELECT 'C6MartPeriodico.PL_D2_S160DettaglioProdottiBF' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Pre' 
	ELSE AREA.ID_AREA 
END AS needarea,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Previdenza'
	WHEN AREA.ID_AREA = 'Na'  THEN 'Non allocate'
	ELSE AREA.NOME_AREA 
END AS needareades,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN  3 
	ELSE AREA.ORDINAMENTO 
END AS areasortorder,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND PATRBF.NOME_PROGETTO IS NULL THEN 'Prodotti non associati a progetti'
	ELSE ltrim(rtrim(PATRBF.NOME_PROGETTO))
END AS nome_progetto,
PATRBF.CHIAVE_PROGETTO as ORDINAMENTO_PROGETTO,
SUM(PATRBF.CTV) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE) AS somma_controval_needarea,
SUM(PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE) AS versato_needarea,
CASE 
	WHEN COUNT(CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END as versato_needareaString,
SUM(MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE) AS MinusPlusValenza_needarea,
CASE 
	WHEN COUNT( CASE 
					WHEN MONIT.MINUS_PLUSVALENZA IS NULL THEN 1 
					ELSE NULL 
				END ) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END AS MinusPlusValenza_needareaString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_progetto) 
	ELSE NULL	
END	AS somma_controval_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_progetto) 
	ELSE NULL
END	AS versato_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_progetto) > 0 
		THEN 'n.d.'
	ELSE NULL
END	AS versato_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_progetto) 
	ELSE NULL
END	AS MinusPlusValenza_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN MONIT.MINUS_PLUSVALENZA IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_progetto) > 0	
		THEN 'n.d.'
	ELSE NULL
END	AS MinusPlusValenza_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.VAR_PERC_PTF
	ELSE NULL
END	AS somma_var_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.COPERTURA
	ELSE NULL
END	AS somma_copertura_need_prog,
RISCHIO_AGGR_AREA.VAR_PERC_PTF AS var_needarea,
CASE 
	WHEN ISNULL(SUM(RISCHIO_AGGR_AREA.COPERTURA) OVER (PARTITION BY AREA.ID_AREA+PATRBF.RETE+PATRBF.COD_FISCALE),0.00) = 0.00 
		THEN 'n.c.' 
--------------------------------------------------------------
--INIZIO INTERVENTI OMNIA QUIII				
	WHEN (SELECT COUNT(*)
	FROM C6MartPeriodico.PATRIMONIO_BF tmp2
	WHERE ISIN in('EURO00000009', 'EURO10000007')
		AND ID_AREA = 'LIQ' and
		tmp2.COD_FISCALE = PATRBF.COD_FISCALE AND
		TMP2.RETE = PATRBF.RETE) = (SELECT COUNT(*)
	FROM C6MartPeriodico.PATRIMONIO_BF tmp3
	WHERE  ID_AREA = 'LIQ' and tmp3.COD_FISCALE = PATRBF.COD_FISCALE AND
		TMP3.RETE = PATRBF.RETE) and AREA.ID_AREA = 'LIQ' 
		THEN 'n.c.' 
--FINE INTERVENTI OMNIA QUIII
--------------------------------------------------------------			
	ELSE NULL 
END AS var_needareaString,
CAST(ISNULL(RISCHIO_AGGR_AREA.COPERTURA,100) AS DECIMAL (5,2)) AS copertura_needarea,
	CASE 
	WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) 
		--THEN '(*) Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
		THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
	ELSE '' 
END AS copertura_needareaString,
RISCHIO_AGGR_PROG.VAR_PERC_PTF AS var_need_prog,
CASE 
	WHEN ISNULL(RISCHIO_AGGR_PROG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
	ELSE NULL 
END AS var_need_progString,
RISCHIO_AGGR_PROG.COPERTURA AS copertura_need_prog,
dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) AS dataSottoscrizione, 
PATRBF.ID_CONTRATTO AS ContrattoDossier, 
--V
CASE WHEN PATRBF.TIPO_PRODOTTO <> 'CC' THEN ANAGPROD.DESCR_PRODOTTO
	 ELSE ANAGPROD.DESCR_PRODOTTO+' '+SUBSTRING(COD_CC,4,2) + '/' + SUBSTRING(COD_CC,6,LEN(ANAG_CC.COD_CC))
END AS Descrizione,
--Bido to get Code_CC field
--NOT AT ALL ANAGPROD.DESCR_PRODOTTO + ' ' + (STUFF(substring(ANAG_CC.COD_CC  , 4 , len(ANAG_CC.COD_CC) - 3), 3 , 0, '/') ) AS Descrizione,
--End Bido
--ANAGPROD.DESCR_PRODOTTO AS Descrizione,
PATRBF.CTV AS Controvalore, 
PATRBF.CTV - MONIT.MINUS_PLUSVALENZA AS VersatoNetto, 
CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 'n.d.' ELSE NULL END as VersatoNettoString,
MONIT.MINUS_PLUSVALENZA AS MinusPlusValenza, 
CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 'n.d.' ELSE NULL END as MinusPlusValenzaString,
--V nuova gestione cc
case when (patrbf.tipo_prodotto ='CC') then 0.00 
else RISCHIO_PROD.VAR_PERC_PTF
end AS VaRprodotto, 
CASE WHEN ISNULL(RISCHIO_PROD.Copertura,0.00) = 0.00 and patrbf.tipo_prodotto <>'CC' THEN 'n.c.' 
     WHEN patrbf.isin in('EURO00000009', 'EURO10000007') THEN 'n.c.'
ELSE NULL END as varProdottoString,
case when (patrbf.tipo_prodotto ='CC') or (patrbf.isin in('EURO00000009', 'EURO10000007')) then 100.00
else RISCHIO_PROD.Copertura 
end AS Coperturaprodotto, 
PATRBF.REND_ANNO AS PerformanceYTD, 
PATRBF.REND_SOTTOSCRIZIONE AS performanceDS,
PARTVIA_DISINV AS partitaViaggiante,
CASE WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) THEN '*' ELSE '' END AS nota_needarea,
RISCHIO_PROD.CREDITRISK as creditrisk,
CASE 
	WHEN ISNULL(RISCHIO_prod.COPERTURA,0.00) = 0.00 and patrbf.tipo_prodotto <> 'CC' THEN 'n.c.' 
	WHEN RISCHIO_PROD.CREDITRISK IS NULL THEN 'n.a.'
		ELSE NULL 
	END as creditriskstring,
--CASE 
--	WHEN RISCHIO_PROD.CREDITRISKEMIT IS NULL THEN 'n.a.'
--		ELSE cast(RISCHIO_PROD.CREDITRISKEMIT as varchar(20))
--	END as creditriskemit
	RISCHIO_PROD.CREDITRISKEMIT as creditriskemit
FROM 
C6MartPeriodico.PATRIMONIO_BF PATRBF
INNER JOIN 
C6MartPeriodico.ANAG_PRODOTTI ANAGPROD 
ON 
	ANAGPROD.COD_PRODOTTO = PATRBF.COD_PRODOTTO
INNER JOIN 
C6MartPeriodico.AREA_BISOGNO AREA 
ON 
	LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA 
LEFT JOIN 
C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
				CASE 
					WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
						THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO+ 
						 '|' + isnull(cast(patrbf.CHIAVE_progetto as varchar),'') + '|'
					when LEFT(PATRBF.ID_AREA,3)='Na' then 'RISFIN|NA|'
					ELSE 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				END
--		END + PATRBF.POSITION_ID 
		+ PATRBF.POSITION_ID 
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_PROG
	ON PATRBF.RETE= RISCHIO_AGGR_PROG.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_PROG.COD_FISCALE
	AND RISCHIO_AGGR_PROG.COD_AGGREG = 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO
		+ '|' +  isnull(cast(patrbf.CHIAVE_progetto as varchar),'')
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_AREA
	ON PATRBF.RETE= RISCHIO_AGGR_AREA.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_AREA.COD_FISCALE
	AND RISCHIO_AGGR_AREA.COD_AGGREG =   case 
		when LEFT(PATRBF.ID_AREA,3) = 'Na' then 'RISFIN|NA'
         else  'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) 
		end
--	AND RISCHIO_AGGR_AREA.COD_AGGREG = 
--		CASE AREA.ID_AREA 
--			WHEN 'Na' THEN 'RISORSENONASSOCIATE' 
--			ELSE 'COMPLESSIVO|BF|' + LEFT(PATRBF.ID_AREA,3) 
--		END
LEFT JOIN
C6MartPeriodico.MONITORAGGIO_ATTUALE MONIT
ON
	PATRBF.RETE = MONIT.RETE
	AND PATRBF.COD_FISCALE = MONIT.COD_FISCALE
	AND LEFT(PATRBF.ID_AREA, 3) = MONIT.ID_AREA
	AND CASE WHEN PATRBF.NOME_PROGETTO IS NULL THEN 'XXX' ELSE PATRBF.NOME_PROGETTO END = MONIT.NOME_PROGETTO
	And patrbf.ordinamento_progetto=monit.ordinamento_progetto
--Bido to get Code_CC field
LEFT OUTER JOIN C6MartPeriodico.ANAG_CC
ON 
	ANAG_CC.COD_FISCALE = PATRBF.COD_FISCALE
	AND ANAG_CC.RETE = PATRBF.RETE
	AND cast(ANAG_CC.cod_cc as integer ) = substring(PATRBF.position_id,72,9)
WHERE 1 = 1 and
	PATRBF.CTV <>0
--GROUP BY PATRBF.COD_FISCALE, PATRBF.RETE, AREA.ID_AREA, AREA.NOME_AREA, AREA.ORDINAMENTO, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO, PATRBF.CTV,
--	MONIT.MINUS_PLUSVALENZA, RISCHIO_AGGR_PROG.COPERTURA, RISCHIO_AGGR_PROG.VAR_PERC_PTF, RISCHIO_AGGR_AREA.VAR_PERC_PTF, RISCHIO_AGGR_AREA.COPERTURA,
--	PATRBF.DATA_SOTTOSCRIZIONE, PATRBF.ID_CONTRATTO, PATRBF.TIPO_PRODOTTO, ANAGPROD.DESCR_PRODOTTO, ANAG_CC.COD_CC, RISCHIO_PROD.VAR_PERC_PTF,
--	RISCHIO_PROD.COPERTURA, PATRBF.ISIN, PATRBF.REND_ANNO, PATRBF.REND_SOTTOSCRIZIONE, PATRBF.PARTVIA_DISINV, RISCHIO_PROD.CREDITRISK, RISCHIO_PROD.CREDITRISKEMIT
ORDER BY 
	AREASORTORDER,CHIAVE_progetto,nome_progetto, PATRBF.CTV DESC
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S162DettaglioProdotti
BEGIN
INSERT INTO WH.PL_D2_S162DettaglioProdotti
	SELECT 'C6MartPeriodico.PL_D2_S162DettaglioProdotti' as ProcedureName, PATRTERZI.RETE as i_rete, PATRTERZI.COD_FISCALE as i_codiceFiscale,	  
		PATRTERZI.DESCR_GRUPPO_PRODOTTO  AS TipoProdotto,
		PATRTERZI.INTERMEDIARIO AS Intermediario,
		dbo.TOSHORTDATESTRING(PATRTERZI.DATA_SOTTOSCRIZIONE) AS DataDiSottoscrizioni, 
		ANAGPRODTERZI.NOME_PRODOTTO AS Descrizione,
		ROUND(PATRTERZI.CTV,2) AS Controvalore, 
		ROUND(PATRTERZI.VERSATO_NETTO,2) AS VersatoNetto, 
		ROUND(PATRTERZI.CTV,2) - ROUND(PATRTERZI.VERSATO_NETTO,2) AS MinusPlusValenza, 
		RISCHIOPROD.VAR_PERC_PTF AS VarPerc,
		CASE 
			WHEN ISNULL(PATRTERZI.VERSATO_NETTO, 0) = 0 THEN 'n.d.' 
			ELSE NULL 
		END AS VersatoNettoString,
		CASE 
			WHEN PATRTERZI.CTV - PATRTERZI.VERSATO_NETTO IS NULL THEN 'n.d.' 
			WHEN ISNULL(PATRTERZI.VERSATO_NETTO, 0) = 0 THEN 'n.d.' 
			ELSE NULL 
		END AS MinusPlusValenzaString,
		CASE
			WHEN ISNULL(RISCHIOPROD.copertura,0.00) = 0.00 THEN 'n.c.' 
			ELSE NULL 
		END AS VarPercString,
		SUM(ROUND(PATRTERZI.CTV,2)) OVER (PARTITION BY PATRTERZI.DESCR_GRUPPO_PRODOTTO,PATRTERZI.COD_FISCALE,PATRTERZI.RETE) AS TotaleCTV,
		SUM(ROUND(PATRTERZI.VERSATO_NETTO,2)) OVER (PARTITION BY PATRTERZI.DESCR_GRUPPO_PRODOTTO,PATRTERZI.COD_FISCALE,PATRTERZI.RETE) AS TotaleVersatoNetto,
		CASE 
			WHEN COUNT(CASE WHEN PATRTERZI.VERSATO_NETTO IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY PATRTERZI.DESCR_GRUPPO_PRODOTTO,PATRTERZI.COD_FISCALE,PATRTERZI.RETE) > 0 THEN 'n.d.' 
			ELSE NULL 
		END AS TotaleVersatoNettoString,
		SUM(ROUND(PATRTERZI.CTV,2) - ROUND(PATRTERZI.VERSATO_NETTO,2)) OVER (PARTITION BY PATRTERZI.DESCR_GRUPPO_PRODOTTO,PATRTERZI.COD_FISCALE,PATRTERZI.RETE) AS TotaleMinus,
		CASE 
			WHEN COUNT(CASE WHEN (PATRTERZI.CTV - PATRTERZI.VERSATO_NETTO) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY PATRTERZI.DESCR_GRUPPO_PRODOTTO,PATRTERZI.COD_FISCALE,PATRTERZI.RETE) > 0 THEN 'n.d.' 
			ELSE NULL 
		END AS TotaleMinusString,
		RISCHIOAGGREG.VAR_PERC_PTF AS TotaleVar,
		CASE WHEN ISNULL(RISCHIOAGGREG.COPERTURA,0.00) = 0.00 THEN 'n.c.' ELSE NULL END AS TotaleVarString,
		RISCHIOAGGREG.COPERTURA AS Copertura_Tot,
		NULL AS Aggiornamento, 
		CASE 
			WHEN RISCHIOAGGREG.COPERTURA > 0 AND RISCHIOAGGREG.COPERTURA < 100 
				THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIOAGGREG.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'
			ELSE '' -- CASI 0, 100, NULL
		END AS Copertura_Totale,
		PATRTERZI.RETE AS Rete, 
		PATRTERZI.COD_FISCALE AS Cod_Fiscale,
		'TABELLA PRODOTTI FINANZIARI ALTRI' AS Tipo,
		CASE WHEN (ISNULL(RISCHIOAGGREG.copertura,100) < 100) THEN '*' ELSE '' END AS Note,
		CASE WHEN PATRTERZI.COD_PRODOTTO = 'PRODOTTO NON IN CATALOGO' AND ISNULL(RISCHIOPROD.copertura,0.00) <> 0.00 THEN 1 ELSE 0	END AS ProdNonInCatalogo,
		CASE UPPER(PATRTERZI.DESCR_GRUPPO_PRODOTTO) 
			WHEN 'FONDI' THEN 0
			WHEN 'GESTIONI PATRIMONIALI' THEN 1
			WHEN 'PRODOTTI DI TIPO AMMINISTRATO (ESCLUSO C/C)' THEN 2
			WHEN 'ASSICURATIVI UNITI/INDEX LINKED' THEN 3
			WHEN 'PORTAFOGLIO GENERICO' THEN 4
			ELSE 10000
		END AS OrdinamentoProdotti,
 RISCHIOPROD.CREDITRISK as creditrisk, 
    CASE 
		WHEN ISNULL(RISCHIOpROD.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		WHEN RISCHIOPROD.CREDITRISK IS NULL THEN 'n.a.'
		ELSE NULL 
	END as creditriskstring,
	RISCHIOPROD.CREDITRISKEMIT as creditriskemit
	FROM 
		C6MartPeriodico.PATRIMONIO_TERZI PATRTERZI
	INNER JOIN 
		C6MartPeriodico.ANAG_PRODOTTI_TERZI ANAGPRODTERZI
		ON 
			PATRTERZI.COD_PRODOTTO_TERZI = ANAGPRODTERZI.COD_PRODOTTO_TERZI
	LEFT OUTER JOIN 
		--[10.10.32.85].C6StampeCentralizzate2.C6MartPeriodico.RISCHIO_AGGREGATO RISCHIOPROD
        C6MartPeriodico.RISCHIO_AGGREGATO RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG ='TIPOPRODTERZI|TERZI|' + PATRTERZI.DESCR_GRUPPO_PRODOTTO + '|'+ PATRTERZI.COD_PRODOTTO_TERZI
	LEFT OUTER JOIN 
		--[10.10.32.85].C6StampeCentralizzate2.C6MartPeriodico.RISCHIO_AGGREGATO RISCHIOAGGREG
        C6MartPeriodico.RISCHIO_AGGREGATO RISCHIOAGGREG
		ON 
			PATRTERZI.RETE = RISCHIOAGGREG.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOAGGREG.COD_FISCALE
			AND RISCHIOAGGREG.COD_AGGREG ='TIPOPRODTERZI|TERZI|' + PATRTERZI.DESCR_GRUPPO_PRODOTTO
	WHERE  1 = 1 
		AND PATRTERZI.DESCR_GRUPPO_PRODOTTO IS NOT NULL
	--GROUP BY PATRTERZI.COD_FISCALE, PATRTERZI.RETE, PATRTERZI.DESCR_GRUPPO_PRODOTTO, PATRTERZI.INTERMEDIARIO, PATRTERZI.DATA_SOTTOSCRIZIONE, ANAGPRODTERZI.NOME_PRODOTTO, PATRTERZI.CTV, PATRTERZI.VERSATO_NETTO,
	--		 RISCHIOPROD.VAR_PERC_PTF, RISCHIOPROD.COPERTURA, RISCHIOAGGREG.VAR_PERC_PTF, RISCHIOAGGREG.COPERTURA, PATRTERZI.COD_PRODOTTO, RISCHIOPROD.CREDITRISK, RISCHIOPROD.CREDITRISKEMIT
	ORDER BY 
		OrdinamentoProdotti, 
		Controvalore DESC
END
-------------------------------------------------------------------------
-------------------------------------------pl_d2_s163patrimoniofinanziariomassetclass
BEGIN
INSERT INTO WH.pl_d2_s163patrimoniofinanziariomassetclass
SELECT DISTINCT 'C6MartPeriodico.pl_d2_s163patrimoniofinanziariomassetclass' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale,
             ASSETCLASS.ORDINAMENTO AS Ordinamento,
             VALORIASSET.ID_ASSETCLASS AS AssetClassId, 
             ASSETCLASS.DESCRIZIONE AS AssetClassName, 
             cast(SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS, RETE,COD_FISCALE) as decimal(19,6)) AS Controvalore,
             (
                    SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS, RETE,COD_FISCALE) /
                    case SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE', RETE,COD_FISCALE)
                    when 0 then 1
                    else SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE', RETE,COD_FISCALE)
                    end 
--                  SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE')
             ) * 100 AS Percentuale,
             cast (SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE', RETE,COD_FISCALE) as decimal(19,6)) AS PatrimonioFinanziarioCTV
       FROM (
             --PRODOTTI TERZI A CATALOGO
             SELECT       
                    PATRTERZI.RETE as RETE,
                    PATRTERZI.COD_FISCALE as COD_FISCALE,
                    ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') AS ID_ASSETCLASS,
                    PATRTERZI.CTV * ISNULL(ASSETPERC.PERC,1) AS Controvalore
             FROM 
                    C6MartPeriodico.PATRIMONIO_TERZI PATRTERZI
             LEFT OUTER JOIN 
                    C6MartPeriodico.ASSET_PERC ASSETPERC 
                    ON 
                           PATRTERZI.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
                           AND ASSETPERC.LIVELLO = 1
             WHERE 1 = 1
                    AND PATRTERZI.COD_PRODOTTO <> 'PRODOTTO NON IN CATALOGO'
             UNION ALL
             --PRODOTTI TERZI NON A CATALOGO
             SELECT 
                    PATRTERZI.RETE as RETE,
                    PATRTERZI.COD_FISCALE as COD_FISCALE,
                    ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') AS ID_ASSETCLASS,
                    PATRTERZI.CTV*ISNULL(ASSETPERC.PERC,1) AS Controvalore
             FROM 
                    C6MartPeriodico.PATRIMONIO_TERZI PATRTERZI
             LEFT OUTER JOIN 
                    C6MartPeriodico.ASSET_PERC_TERZI ASSETPERC 
                    ON 
                           PATRTERZI.COD_PRODOTTO_TERZI = ASSETPERC.COD_PRODOTTO_TERZI
                           AND ASSETPERC.LIVELLO = 1
             WHERE 1 = 1
                    AND PATRTERZI.COD_PRODOTTO = 'PRODOTTO NON IN CATALOGO'
       ) VALORIASSET
       INNER JOIN C6MartPeriodico.ASSETCLASS ASSETCLASS
             ON 
                    ASSETCLASS.ID_ASSETCLASS = VALORIASSET.ID_ASSETCLASS
      -- GROUP BY COD_FISCALE, RETE, ASSETCLASS.ORDINAMENTO, ASSETCLASS.ID_ASSETCLASS, VALORIASSET.ID_ASSETCLASS, ASSETCLASS.DESCRIZIONE, VALORIASSET.CONTROVALORE
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S164PolizzeAltriIstituti
BEGIN
INSERT INTO WH.PL_D2_S164PolizzeAltriIstituti
	SELECT  'C6MartPeriodico.PL_D2_S164PolizzeAltriIstituti' as ProcedureName, PATRTERZI.RETE as i_rete, PATRTERZI.COD_FISCALE as i_codiceFiscale,	     
		PATRTERZI.INTERMEDIARIO AS Intermediario,
		dbo.toShortDateString(PATRTERZI.DATA_SOTTOSCRIZIONE) AS DataDiSottoscrizione,
		dbo.toShortDateString(PATRTERZI.DATA_SCADENZA) AS DataDiScadenza,
		PATRTERZI.TIPO_POLIZZA AS TipologiaPolizza, 
		ANAGTERZI.NOME_PRODOTTO AS Descrizione,
		NULL AS Aggiornamento, 
		PATRTERZI.CTV AS PrestazioneAssicurata, 
		PATRTERZI.TIPO_PRODOTTO AS TipoVersamento, 
		PATRTERZI.VERSATO_NETTO  AS AmmontareVersamento 
	FROM 
		C6MartPeriodico.PATRIMONIO_TERZI AS PATRTERZI
	INNER JOIN 
		C6MartPeriodico.ANAG_PRODOTTI_TERZI AS ANAGTERZI
		ON 
			PATRTERZI.COD_PRODOTTO_TERZI = ANAGTERZI.COD_PRODOTTO_TERZI 			
			AND ANAGTERZI.DESCR_PRODOTTO = 'Assets.FinancialAssets.PolizzeRivalutabili'
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S165FondiAltriIstituti
BEGIN
	INSERT INTO WH.PL_D2_S165FondiAltriIstituti
	SELECT  'C6MartPeriodico.PL_D2_S165FondiAltriIstituti' as ProcedureName, PATRTERZI.RETE as i_rete, PATRTERZI.COD_FISCALE as i_codiceFiscale,	     
		PATRTERZI.INTERMEDIARIO AS Intermediario,
		ANAGPRODTERZI.NOME_PRODOTTO AS descrizione_prodotto,
		dbo.ToShortDateString(PATRTERZI.DATA_SOTTOSCRIZIONE) AS DataSottoscrizione,
		PATRTERZI.FREQ_RATA as tipo_versamento,
		PATRTERZI.CTV as controvalore,
		PATRTERZI.VERSATO_NETTO as ammontare,
		SUM(PATRTERZI.CTV) OVER (PARTITION BY 'TOTALE') as somma_controval,
		RISCHIOPROD.VAR_PERC_PTF as Var_Prodotto,
		CASE WHEN RISCHIOPROD.VAR_PERC_PTF IS NULL OR ISNULL(RISCHIOPROD.COPERTURA,0.00) = 0.00 THEN 'n.c.' ELSE NULL END as Var_ProdottoString,
		RISCHIOAGGR.VAR_PERC_PTF as Var_Totale,
		CASE WHEN RISCHIOAGGR.VAR_PERC_PTF IS NULL OR ISNULL(RISCHIOAGGR.COPERTURA,0.00) = 0.00 THEN 'n.c.' ELSE NULL END as Var_TotaleString,
		--CASE WHEN (ISNULL(RISCHIOAGGR.COPERTURA,100) < 100) THEN '(*) Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIOAGGR.COPERTURA AS decimal (5,2)) AS varchar),'.',',') + '%'  ELSE '' END AS copertura_totale,	
		CASE 
			WHEN RISCHIOAGGR.COPERTURA > 0 AND RISCHIOAGGR.COPERTURA < 100 
				THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIOAGGR.COPERTURA AS decimal (5,2)) AS varchar),'.',',') + '%'  
			ELSE '' -- CASI 0, 100, NULL
		END AS copertura_totale,	
		CASE WHEN RISCHIOAGGR.COPERTURA > 0 AND RISCHIOAGGR.COPERTURA < 100 THEN '*' ELSE '' END as Nota,
		CASE WHEN PATRTERZI.COD_PRODOTTO = 'PRODOTTO NON IN CATALOGO' THEN 1 ELSE 0	END AS ProdNonInCatalogo,
        RISCHIOAGGR.CREDITRISK as creditrisk,
    CASE 
		WHEN ISNULL(RISCHIOAGGR.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		WHEN RISCHIOAGGR.CREDITRISK IS NULL THEN 'n.a.'
		ELSE NULL 
	END as creditriskstring
	FROM 
		C6MartPeriodico.PATRIMONIO_TERZI AS PATRTERZI
	INNER JOIN 
		C6MartPeriodico.ANAG_PRODOTTI_TERZI AS ANAGPRODTERZI
		ON 
			PATRTERZI.COD_PRODOTTO_TERZI = ANAGPRODTERZI.COD_PRODOTTO_TERZI
			--AND ANAGPRODTERZI.ALBERO_PRODOTTI = 'Ass.Prev'
			AND ANAGPRODTERZI.DESCR_PRODOTTO='Assets.FinancialAssets.ProdottiPrevidenziali'
	LEFT OUTER JOIN 
		C6MartPeriodico.RISCHIO_AGGREGATO AS RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG = 'TIPOPRODTERZI|TERZI|' + ISNULL(DESCR_GRUPPO_PRODOTTO,PATRTERZI.TIPO_PRODOTTO) + '|' + PATRTERZI.cod_prodotto_terzi
	LEFT OUTER JOIN 
		C6MartPeriodico.RISCHIO_AGGREGATO AS RISCHIOAGGR
		ON 
			PATRTERZI.RETE = RISCHIOAGGR.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOAGGR.COD_FISCALE
			AND RISCHIOAGGR.COD_AGGREG = 'TIPOPRODTERZI|TERZI|' + ISNULL(DESCR_GRUPPO_PRODOTTO,PATRTERZI.TIPO_PRODOTTO)
	--	GROUP BY 
	--	PATRTERZI.COD_FISCALE, PATRTERZI.RETE, PATRTERZI.intermediario, ANAGPRODTERZI.NOME_PRODOTTO, PATRTERZI.DATA_SOTTOSCRIZIONE, PATRTERZI.FREQ_RATA,
	--	PATRTERZI.CTV, PATRTERZI.VERSATO_NETTO, RISCHIOPROD.VAR_PERC_PTF, RISCHIOPROD.COPERTURA,  RISCHIOAGGR.VAR_PERC_PTF, RISCHIOAGGR.COPERTURA, 
	--	PATRTERZI.COD_PRODOTTO, RISCHIOAGGR.CREDITRISK
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S167DistribuzioneRischioCredito
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
INSERT INTO WH.PL_D2_S167DistribuzioneRischioCredito
	SELECT  'C6MartPeriodico.PL_D2_S167DistribuzioneRischioCredito' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale,	  
RETE,
COD_FISCALE,
INTERMEDIARIO,
CASE WHEN INTERMEDIARIO  IN ( 'Fideuram', 'Sanpaolo Invest') THEN 1
     ELSE 2 END AS ORDINE,
SUM(CTV)  AS CTV_TOT,
SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)  AS CTV_notCovered,
SUM(CASE WHEN RISKCLASS = 'Classe A' 
				or RISKCLASS = 'Classe B'
					or RISKCLASS = 'Classe C' 
						or RISKCLASS = 'Classe D' 
	THEN CTV ELSE 0 END)  AS CTV_CreditRisk,
SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END)  AS CTV_na,
--CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)/SUM(CTV))*100  END AS PERC_notCovered,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'Classe A' 
												or RISKCLASS = 'Classe B'
													or RISKCLASS = 'Classe C' 
														or RISKCLASS = 'Classe D' THEN CTV ELSE 0 END)
									/SUM(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END) 
)*100 END AS PERC_CreditRisk,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END) /sum(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END))*100  END as PERC_NA
FROM
(
 -- Start 1.1
SELECT 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END AS RISKCLASS,
CASE WHEN PATRBF.RETE = 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' END AS INTERMEDIARIO,
--SUM(CASE WHEN PATRBF.ID_AREA = 'Cc' AND PATRBF.CTV < 0 THEN 0 ELSE PATRBF.CTV END) AS CTV
SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area in ('cc','self') THEN 0 ELSE PATRBF.CTV END) AS ctv
FROM
[C6Martperiodico].PATRIMONIO_BF PATRBF
---Per calcolare la somma algebrica dei cc 
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area in ('Cc','Self')
group by cod_fiscale, rete
) ctvcc
on 
patrbf.cod_fiscale=ctvcc.cod_fiscale
and
patrbf.rete=ctvcc.rete
--fine calcolo somma cc
LEFT OUTER JOIN
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
			CASE 
				WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO + '|' + isnull(cast(PATRBF.ordinamento_progetto as varchar),'') + '|'
				--V
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('EXT','INV','PRE','RIS','LIQ')
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('CC')
					THEN 'COMPLESSIVO|BF|CC|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('SELF')
					THEN 'COMPLESSIVO|BF|SELF|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('NA')
					THEN 'RISFIN|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				--
			END	+ PATRBF.POSITION_ID 
--INNER JOIN C6MartPeriodico.CODIFICA_CREDITRISK CR
LEFT outer JOIN C6MartPeriodico.CODIFICA_CREDITRISK CR
ON RISCHIO_PROD.CREDITRISK = cr.profilo
--V
--
GROUP BY 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END,
CASE WHEN PATRBF.RETE = 'F' THEN 'FIDEURAM' ELSE 'SANPAOLO' END
--- End 1.1
UNION ALL
-- Start 1.2
SELECT  
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
'Altri Istituti' AS INTERMEDIARIO,
--PATRTERZI.INTERMEDIARIO,
SUM(ROUND(CTV,2)) AS CTV
FROM 
[C6Martperiodico].PATRIMONIO_TERZI PATRTERZI
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6Martperiodico].pATRIMONIO_terzi
where tipo_prodotto='Conti correnti'
group by cod_fiscale, rete
) ctvcc
on
patrterzi.cod_fiscale=ctvcc.cod_fiscale
and
patrterzi.rete=ctvcc.rete
LEFT OUTER JOIN 
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG ='TIPOPRODTERZI|TERZI|' +ISNULL(PATRTERZI.DESCR_GRUPPO_PRODOTTO, PATRTERZI.TIPO_PRODOTTO)  + '|'+ PATRTERZI.COD_PRODOTTO_TERZI
left outer JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIOPROD.CREDITRISK = cr.profilo
--V
--
GROUP BY 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
--PATRTERZI.INTERMEDIARIO,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
-- End 1.2
)H
GROUP BY
RETE,
COD_FISCALE,
INTERMEDIARIO
--------
UNION ALL
-----------
--QUERY TOTALE
SELECT  'C6MartPeriodico.PL_D2_S167DistribuzioneRischioCredito' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale, 
RETE,
COD_FISCALE,
'Complessivo' AS INTERMEDIARIO,
3 AS ORDINE,
SUM(CTV)  AS CTV_TOT,
SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)  AS CTV_notCovered,
SUM(CASE WHEN RISKCLASS = 'Classe A' 
				or RISKCLASS = 'Classe B'
					or RISKCLASS = 'Classe C' 
						or RISKCLASS = 'Classe D' 
	THEN CTV ELSE 0 END)  AS CTV_CreditRisk,
SUM(CASE WHEN RISKCLASS ='NA' THEN CTV ELSE 0 END)  AS CTV_na,
--CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)/SUM(CTV))*100  END AS PERC_notCovered,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'Classe A' 
												or RISKCLASS = 'Classe B'
													or RISKCLASS = 'Classe C' 
														or RISKCLASS = 'Classe D' THEN CTV ELSE 0 END)
									/SUM(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END) 
)*100 END AS PERC_CreditRisk,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END) /sum(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END))*100 END as PERC_NA
FROM
(
--- Start 2.1
SELECT 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
--SUM(CASE WHEN PATRBF.ID_AREA = 'Cc' AND PATRBF.CTV < 0 THEN 0 ELSE PATRBF.CTV END) AS CTV
SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area in ('cc','self')  THEN 0 ELSE PATRBF.CTV END) AS CTV
FROM
[C6Martperiodico].PATRIMONIO_BF PATRBF
--per fare la somma algebrica dei cc
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area in ('Cc','Self')
group by cod_fiscale, rete
) ctvcc
on 
patrbf.cod_fiscale=ctvcc.cod_fiscale
and
patrbf.rete=ctvcc.rete
--fine somma cc
LEFT OUTER JOIN
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
			CASE 
				WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO+ '|' + isnull(cast(PATRBF.ordinamento_progetto as varchar),'')+'|'
				--V
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('EXT','INV','PRE','RIS','LIQ')
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('CC')
					THEN 'COMPLESSIVO|BF|CC|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('SELF')
					THEN 'COMPLESSIVO|BF|SELF|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('NA')
					THEN 'RISFIN|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				--
			END	+ PATRBF.POSITION_ID 
left outer JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIO_PROD.CREDITRISK = cr.profilo
--V
--
GROUP BY 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
-- End 2.1
UNION ALL
-- Start 2.2
SELECT 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
SUM(ROUND(CTV,2)) AS CTV
FROM 
[C6Martperiodico].PATRIMONIO_TERZI PATRTERZI
left outer join
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from 
[C6Martperiodico].pATRIMONIO_terzi
where tipo_prodotto='Conti correnti'
group by cod_fiscale, rete
) ctvcc
on
patrterzi.cod_fiscale=ctvcc.cod_fiscale
and
patrterzi.rete=ctvcc.rete
LEFT OUTER JOIN 
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG ='TIPOPRODTERZI|TERZI|' + ISNULL(PATRTERZI.DESCR_GRUPPO_PRODOTTO, PATRTERZI.TIPO_PRODOTTO)  + '|'+ PATRTERZI.COD_PRODOTTO_TERZI
left outer  JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIOPROD.CREDITRISK = cr.profilo
--
GROUP BY 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
--- End 2.2
)H
GROUP BY
RETE,
COD_FISCALE
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S168TabellaEmittenti
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
INSERT INTO WH.PL_D2_S168TabellaEmittenti
	SELECT  'C6MartPeriodico.PL_D2_S168TabellaEmittenti' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceFiscale,	  
		COD_FISCALE,
		RETE,
		RATING_AAA,
		RATING_AAp,
		RATING_AA,
		RATING_AAm,
		RATING_Ap,
		RATING_A,
		RATING_Am,
		RATING_BBBp,
		RATING_BBB,
		RATING_BBBm,
		RATING_BBp,
		RATING_BB,
		RATING_BBm,
		RATING_Bp,
		RATING_B,
		RATING_Bm,
		RATING_CCCp,
		RATING_CCC,
		RATING_CCCm,
		RATING_CC,
		RATING_C,
		RATING_D,
		RATING_na,
		FLG_RISKCLASS1,
		FLG_RISKCLASS2,
		FLG_RISKCLASS3,
		FLG_RISKCLASS4,
		FLG_RISKCLASS5,
		FLG_RISKCLASS6,
		FLG_RISKCLASS7,
		FLG_RISKCLASS8,
		FLG_RISKCLASS9,
		FLG_RISKCLASS10,
		INTERMEDIARIO,
		ISSUER,
		STOCKSCounterValue,
		bondsCounterValue,
		CONCENTRATION_ISSUER,
		CONCENTRATION,
		NC
--isnull(RATING,'n.a.') as RATING
FROM
(
-- PER INTERMEDIARIO 
    SELECT
			COD_FISCALE,
			RETE,
			MAX(RATING_AAA) AS RATING_AAA,
			MAX(RATING_AAp) AS RATING_AAp,
			MAX(RATING_AA) AS RATING_AA,
			MAX(RATING_AAm) AS RATING_AAm,
			MAX(RATING_Ap) AS RATING_Ap,
			MAX(RATING_A) AS RATING_A,
			MAX(RATING_Am) AS RATING_Am,
			MAX(RATING_BBBp) AS RATING_BBBp,
			MAX(RATING_BBB) AS RATING_BBB,
			MAX(RATING_BBBm) AS RATING_BBBm,
			MAX(RATING_BBp) AS RATING_BBp,
			MAX(RATING_BB) AS RATING_BB,
			MAX(RATING_BBm) AS RATING_BBm,
			MAX(RATING_Bp) AS RATING_Bp,
			MAX(RATING_B) AS RATING_B,
			MAX(RATING_Bm) AS RATING_Bm,
			MAX(RATING_CCCp) AS RATING_CCCp,
			MAX(RATING_CCC) AS RATING_CCC,
			MAX(RATING_CCCm) AS RATING_CCCm,
			MAX(RATING_CC) AS RATING_CC,
			MAX(RATING_C) AS RATING_C,
			MAX(RATING_D) AS RATING_D,
			MAX(RATING_na) AS RATING_na,
			MAX(FLG_RISKCLASS1) AS FLG_RISKCLASS1,
			MAX(FLG_RISKCLASS2) AS FLG_RISKCLASS2,
			MAX(FLG_RISKCLASS3) AS FLG_RISKCLASS3,
			MAX(FLG_RISKCLASS4) AS FLG_RISKCLASS4,
			MAX(FLG_RISKCLASS5) AS FLG_RISKCLASS5,
			MAX(FLG_RISKCLASS6) AS FLG_RISKCLASS6,
			MAX(FLG_RISKCLASS7) AS FLG_RISKCLASS7,
			MAX(FLG_RISKCLASS8) AS FLG_RISKCLASS8,
			MAX(FLG_RISKCLASS9) AS FLG_RISKCLASS9,
			MAX(FLG_RISKCLASS10) AS FLG_RISKCLASS10,
			--V nel caso sia null è BF???
			isnull(INTERMEDIARIO,'BF') AS INTERMEDIARIO,
			EMITTENTE AS ISSUER,
			SUM(STOCKSCounterValue) AS  STOCKSCounterValue,
			sum(bondsCounterValue) AS bondsCounterValue,
			0 as  CONCENTRATION_ISSUER ,
			--V normalizzo la percentuale per essere rappresentato sul report
			MAX(CONCENTRATION)* 100 AS CONCENTRATION,
			sum(case when copertura > 0 then 0 else 1 end) as nc
			--RATING as RATING
				FROM
				(
					SELECT      V.COD_FISCALE,
								V.RETE,
								INTERMEDIARIO,
								CREDITRISKCLASS,
								EMITTENTE,
								CASE WHEN RATING = 'AAA' THEN 1 ELSE 0 END AS RATING_AAA,
								CASE WHEN RATING = 'AA+' THEN 1 ELSE 0 END AS RATING_AAp,
								CASE WHEN RATING = 'AA' THEN 1 ELSE 0 END AS RATING_AA,
								CASE WHEN RATING = 'AA-' THEN 1 ELSE 0 END AS RATING_AAm,
								CASE WHEN RATING = 'A+' THEN 1 ELSE 0 END AS RATING_Ap,
								CASE WHEN RATING = 'A' THEN 1 ELSE 0 END AS RATING_A,
								CASE WHEN RATING = 'A-' THEN 1 ELSE 0 END AS RATING_Am,
								CASE WHEN RATING = 'BBB+' THEN 1 ELSE 0 END AS RATING_BBBp,
								CASE WHEN RATING = 'BBB' THEN 1 ELSE 0 END AS RATING_BBB,
								CASE WHEN RATING = 'BBB-' THEN 1 ELSE 0 END AS RATING_BBBm,
								CASE WHEN RATING = 'BB+' THEN 1 ELSE 0 END AS RATING_BBp,
								CASE WHEN RATING = 'BB' THEN 1 ELSE 0 END AS RATING_BB,
								CASE WHEN RATING = 'BB-' THEN 1 ELSE 0 END AS RATING_BBm,
								CASE WHEN RATING = 'B+' THEN 1 ELSE 0 END AS RATING_Bp,
								CASE WHEN RATING = 'B' THEN 1 ELSE 0 END AS RATING_B,
								CASE WHEN RATING = 'B-' THEN 1 ELSE 0 END AS RATING_Bm,
								CASE WHEN RATING = 'CCC+' THEN 1 ELSE 0 END AS RATING_CCCp,
								CASE WHEN RATING = 'CCC' THEN 1 ELSE 0 END AS RATING_CCC,
								CASE WHEN RATING = 'CCC-' THEN 1 ELSE 0 END AS RATING_CCCm,
								CASE WHEN RATING = 'CC' THEN 1 ELSE 0 END AS RATING_CC,
								CASE WHEN RATING = 'C' THEN 1 ELSE 0 END AS RATING_C,
								CASE WHEN RATING = 'D' THEN 1 ELSE 0 END AS RATING_D,
								CASE WHEN RATING is null THEN 1 ELSE 0 END AS RATING_na, 
								CASE WHEN CREDITRISKCLASS ='Rischio 1/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS1,
								CASE WHEN CREDITRISKCLASS ='Rischio 2/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS2,
								CASE WHEN CREDITRISKCLASS ='Rischio 3/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS3,
								CASE WHEN CREDITRISKCLASS ='Rischio 4/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS4,
								CASE WHEN CREDITRISKCLASS ='Rischio 5/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS5,
								CASE WHEN CREDITRISKCLASS ='Rischio 6/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS6,
								CASE WHEN CREDITRISKCLASS ='Rischio 7/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS7,
								CASE WHEN CREDITRISKCLASS ='Rischio 8/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS8,
								CASE WHEN CREDITRISKCLASS ='Rischio 9/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS9,
								CASE WHEN CREDITRISKCLASS ='Rischio 10/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS10,
								SUM(CTV_AZ_OB_EMIT) as CTV_AZ_OB_EMIT,
								SUM(CTV_PRODOTTO) AS CTV_PRODOTTO,
								sum(CTV_AZIONARIO) AS STOCKSCounterValue,
								sum(CTV_OBBLIGAZIONARIO) AS bondsCounterValue,
								0 AS  CONCENTRATION_ISSUER ,
								SUM(CTV_AZ_OB_EMIT_INTER)/SUM(CTV_COMPL_NOCC_NEG)  AS CONCENTRATION,
								sum(copertura) as copertura
								--RATING as RATING
				 FROM  C6MARTPERIODICO.PATRIMONIO_EMITTENTI V  
				LEFT JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAG
					   ON V.COD_PRODOTTO = ANAG.COD_PRODOTTO
				 WHERE 
				 1=1				
				   AND (CTV_AZIONARIO >0 OR CTV_OBBLIGAZIONARIO > 0)
				GROUP BY
				 V.COD_FISCALE,
				 V.RETE,
				 INTERMEDIARIO,
				 EMITTENTE,
				 CREDITRISKCLASS,
				  RATING
				) Y
GROUP BY 
     COD_FISCALE,
     RETE,
     INTERMEDIARIO,
     EMITTENTE 
--RATING
--V devo rappresentare solo le 3 principali me le ordine e nel codice scorro per le prime 3 dopo aver filtrato per intermediario
--ORDER BY CONCENTRATION DESC
UNION 
--COMPLESSIVO
   SELECT
   COD_FISCALE,
			RETE,
        MAX(RATING_AAA) AS RATING_AAA,
		MAX(RATING_AAp) AS RATING_AAp,
		MAX(RATING_AA) AS RATING_AA,
		MAX(RATING_AAm) AS RATING_AAm,
		MAX(RATING_Ap) AS RATING_Ap,
		MAX(RATING_A) AS RATING_A,
		MAX(RATING_Am) AS RATING_Am,
		MAX(RATING_BBBp) AS RATING_BBBp,
		MAX(RATING_BBB) AS RATING_BBB,
		MAX(RATING_BBBm) AS RATING_BBBm,
		MAX(RATING_BBp) AS RATING_BBp,
		MAX(RATING_BB) AS RATING_BB,
		MAX(RATING_BBm) AS RATING_BBm,
		MAX(RATING_Bp) AS RATING_Bp,
		MAX(RATING_B) AS RATING_B,
		MAX(RATING_Bm) AS RATING_Bm,
		MAX(RATING_CCCp) AS RATING_CCCp,
		MAX(RATING_CCC) AS RATING_CCC,
		MAX(RATING_CCCm) AS RATING_CCCm,
		MAX(RATING_CC) AS RATING_CC,
		MAX(RATING_C) AS RATING_C,
		MAX(RATING_D) AS RATING_D,
		MAX(RATING_na) AS RATING_na,
     MAX(FLG_RISKCLASS1) AS FLG_RISKCLASS1,
     MAX(FLG_RISKCLASS2) AS FLG_RISKCLASS2,
     MAX(FLG_RISKCLASS3) AS FLG_RISKCLASS3,
     MAX(FLG_RISKCLASS4) AS FLG_RISKCLASS4,
	MAX(FLG_RISKCLASS5) AS FLG_RISKCLASS5,
	MAX(FLG_RISKCLASS6) AS FLG_RISKCLASS6,
	MAX(FLG_RISKCLASS7) AS FLG_RISKCLASS7,
	MAX(FLG_RISKCLASS8) AS FLG_RISKCLASS8,
	MAX(FLG_RISKCLASS9) AS FLG_RISKCLASS9,
	MAX(FLG_RISKCLASS10) AS FLG_RISKCLASS10,
	 isnull(INTERMEDIARIO,'BF') AS INTERMEDIARIO,
     EMITTENTE AS ISSUER,
     SUM(STOCKSCounterValue) AS  STOCKSCounterValue,
     SUM(bondsCounterValue) AS bondsCounterValue,
     SUM(isnull(bondsCounterValue,0)+ isnull(STOCKSCounterValue,0))/ 
	 (select sum(ctv_prodotto) from 
		c6martperiodico.patrimonio_emittenti 
		where cod_fiscale = L.COD_FISCALE and rete = L.RETE
		and  ctv_prodotto > 0)  
	 *100  CONCENTRATION_ISSUER ,
     0 AS CONCENTRATION,
	sum(case when copertura > 0 then 0 else 1 end) as nc
--RATING as RATING
FROM
(
SELECT 
COD_FISCALE,
RETE,
'COMPLESSIVO' as INTERMEDIARIO,
CREDITRISKCLASS,
EMITTENTE,
RATING_AAA,
RATING_AAp,
RATING_AA,
RATING_AAm,
RATING_Ap,
RATING_A,
RATING_Am,
RATING_BBBp,
RATING_BBB,
RATING_BBBm,
RATING_BBp,
RATING_BB,
RATING_BBm,
RATING_Bp,
RATING_B,
RATING_Bm,
RATING_CCCp,
RATING_CCC,
RATING_CCCm,
RATING_CC,
RATING_C,
RATING_D,
RATING_na,
FLG_RISKCLASS1,
FLG_RISKCLASS2,
FLG_RISKCLASS3,
FLG_RISKCLASS4,
FLG_RISKCLASS5,
FLG_RISKCLASS6,
FLG_RISKCLASS7,
FLG_RISKCLASS8,
FLG_RISKCLASS9,
FLG_RISKCLASS10,
SUM(CTV_AZ_OB_EMIT) CTV_AZ_OB_EMIT,
SUM(STOCKSCounterValue) AS STOCKSCounterValue,
SUM(bondsCounterValue) AS bondsCounterValue,
0 AS CONCENTRATION_ISSUER,
SUM(CTV_AZ_OB_EMIT_INTER)/SUM(CTV_COMPLessivo) TOT ,
SUM(COPERTURA) AS COPERTURA 
--RATING as RATING
FROM
(
SELECT     V.COD_FISCALE,
                V.RETE,
                'COMPLESSIVO' as INTERMEDIARIO,
                CREDITRISKCLASS,
                EMITTENTE,
                 CASE WHEN RATING = 'AAA' THEN 1 ELSE 0 END AS RATING_AAA,
					CASE WHEN RATING = 'AA+' THEN 1 ELSE 0 END AS RATING_AAp,
					CASE WHEN RATING = 'AA' THEN 1 ELSE 0 END AS RATING_AA,
					CASE WHEN RATING = 'AA-' THEN 1 ELSE 0 END AS RATING_AAm,
					CASE WHEN RATING = 'A+' THEN 1 ELSE 0 END AS RATING_Ap,
					CASE WHEN RATING = 'A' THEN 1 ELSE 0 END AS RATING_A,
					CASE WHEN RATING = 'A-' THEN 1 ELSE 0 END AS RATING_Am,
					CASE WHEN RATING = 'BBB+' THEN 1 ELSE 0 END AS RATING_BBBp,
					CASE WHEN RATING = 'BBB' THEN 1 ELSE 0 END AS RATING_BBB,
					CASE WHEN RATING = 'BBB-' THEN 1 ELSE 0 END AS RATING_BBBm,
					CASE WHEN RATING = 'BB+' THEN 1 ELSE 0 END AS RATING_BBp,
					CASE WHEN RATING = 'BB' THEN 1 ELSE 0 END AS RATING_BB,
					CASE WHEN RATING = 'BB-' THEN 1 ELSE 0 END AS RATING_BBm,
					CASE WHEN RATING = 'B+' THEN 1 ELSE 0 END AS RATING_Bp,
					CASE WHEN RATING = 'B' THEN 1 ELSE 0 END AS RATING_B,
					CASE WHEN RATING = 'B-' THEN 1 ELSE 0 END AS RATING_Bm,
					CASE WHEN RATING = 'CCC+' THEN 1 ELSE 0 END AS RATING_CCCp,
					CASE WHEN RATING = 'CCC' THEN 1 ELSE 0 END AS RATING_CCC,
					CASE WHEN RATING = 'CCC-' THEN 1 ELSE 0 END AS RATING_CCCm,
					CASE WHEN RATING = 'CC' THEN 1 ELSE 0 END AS RATING_CC,
					CASE WHEN RATING = 'C' THEN 1 ELSE 0 END AS RATING_C,
					CASE WHEN RATING = 'D' THEN 1 ELSE 0 END AS RATING_D,
					CASE WHEN RATING is null THEN 1 ELSE 0 END AS RATING_na, 
				CASE WHEN CREDITRISKCLASS ='Rischio 1/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS1,
				CASE WHEN CREDITRISKCLASS ='Rischio 2/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS2,
				CASE WHEN CREDITRISKCLASS ='Rischio 3/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS3,
				CASE WHEN CREDITRISKCLASS ='Rischio 4/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS4,
				CASE WHEN CREDITRISKCLASS ='Rischio 5/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS5,
				CASE WHEN CREDITRISKCLASS ='Rischio 6/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS6,
				CASE WHEN CREDITRISKCLASS ='Rischio 7/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS7,
				CASE WHEN CREDITRISKCLASS ='Rischio 8/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS8,
				CASE WHEN CREDITRISKCLASS ='Rischio 9/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS9,
				CASE WHEN CREDITRISKCLASS ='Rischio 10/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS10,
                SUM(CTV_AZ_OB_EMIT) as CTV_AZ_OB_EMIT,
                SUM(CTV_AZIONARIO) AS STOCKSCounterValue,
                sum(CTV_OBBLIGAZIONARIO) AS bondsCounterValue,
                0 AS  CONCENTRATION_ISSUER ,
                SUM(CTV_AZ_OB_EMIT_INTER) CTV_AZ_OB_EMIT_INTER,
                SUM(CTV_COMPLessivo)  AS CTV_COMPLessivo,
                MAX(copertura) as copertura
				--RATING as RATING
 FROM  C6MARTPERIODICO.PATRIMONIO_EMITTENTI V 
LEFT JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAG
	   ON V.COD_PRODOTTO = ANAG.COD_PRODOTTO 
 WHERE 
 1=1
   AND (CTV_AZIONARIO >0 OR CTV_OBBLIGAZIONARIO > 0)
GROUP BY
 V.COD_FISCALE,
 V.RETE,
 EMITTENTE,
 INTERMEDIARIO,
 CREDITRISKCLASS,
RATING
) Y
GROUP BY 
COD_FISCALE,
RETE,
INTERMEDIARIO,
CREDITRISKCLASS,
EMITTENTE,
	RATING_AAA,
RATING_AAp,
RATING_AA,
RATING_AAm,
RATING_Ap,
RATING_A,
RATING_Am,
RATING_BBBp,
RATING_BBB,
RATING_BBBm,
RATING_BBp,
RATING_BB,
RATING_BBm,
RATING_Bp,
RATING_B,
RATING_Bm,
RATING_CCCp,
RATING_CCC,
RATING_CCCm,
RATING_CC,
RATING_C,
RATING_D,
RATING_na,
FLG_RISKCLASS1,
FLG_RISKCLASS2,
FLG_RISKCLASS3,
FLG_RISKCLASS4,
FLG_RISKCLASS5,
FLG_RISKCLASS6,
FLG_RISKCLASS7,
FLG_RISKCLASS8,
FLG_RISKCLASS9,
FLG_RISKCLASS10
--RATING
) L
GROUP BY 
     COD_FISCALE,
     RETE,
     INTERMEDIARIO,
     EMITTENTE 
--RATING
--V devo rappresentare solo le 3 principali me le ordine e nel codice scorro per le prime 3 dopo aver filtrato per intermediario
--ORDER BY CONCENTRATION DESC
) U
ORDER BY CONCENTRATION DESC , CONCENTRATION_ISSUER DESC 
END
-------------------------------------------------------------------------
-----------------------------------------------PL_S43DettaglioProdottiBF
BEGIN
SELECT COUNT(*) as TOTSELFLIQ, PATRIMONIO_BF.COD_FISCALE, PATRIMONIO_BF.RETE
	INTO #TOTSELFLIQ
	FROM C6MARTPERIODICO.PATRIMONIO_BF
	WHERE  ISIN in('EURO00000009', 'EURO10000007')
		AND ID_AREA = 'LIQ'
	GROUP BY PATRIMONIO_BF.COD_FISCALE, PATRIMONIO_BF.RETE
	SELECT COUNT(*) as TOTLIQ, PATRIMONIO_BF.COD_FISCALE, PATRIMONIO_BF.RETE
	INTO #TOTLIQ
	FROM C6MARTPERIODICO.PATRIMONIO_BF
	WHERE ID_AREA = 'LIQ'
	GROUP BY PATRIMONIO_BF.COD_FISCALE, PATRIMONIO_BF.RETE
INSERT INTO WH.PL_S43DettaglioProdottiBF    
--FINE INTERVENTI OMNIA QUIII
--------------------------------------------------------------------------------------
SELECT   'C6MartPeriodico.PL_S43DettaglioProdottiBF' as ProcedureName, PATRBF.RETE, PATRBF.COD_FISCALE ,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Pre' 
	ELSE AREA.ID_AREA 
END AS needarea,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Previdenza'
	WHEN AREA.ID_AREA = 'Na'  THEN 'Non allocate'
	ELSE AREA.NOME_AREA 
END AS needareades,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN  3 
	ELSE AREA.ORDINAMENTO 
END AS areasortorder,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND PATRBF.NOME_PROGETTO IS NULL THEN 'Prodotti non associati a progetti'
	ELSE ltrim(rtrim(PATRBF.NOME_PROGETTO))
END AS nome_progetto,
PATRBF.CHIAVE_PROGETTO AS ORDINAMENTO_PROGETTO,
SUM(PATRBF.CTV) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE) AS somma_controval_needarea,
SUM(PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE) AS versato_needarea,
CASE 
	WHEN COUNT(CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END as versato_needareaString,
SUM(MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE) AS MinusPlusValenza_needarea,
CASE 
	WHEN COUNT( CASE 
					WHEN MONIT.MINUS_PLUSVALENZA IS NULL THEN 1 
					ELSE NULL 
				END ) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END AS MinusPlusValenza_needareaString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV) OVER (PARTITION BY AREA.ID_AREA, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO,PATRBF.RETE, PATRBF.COD_FISCALE) 
	ELSE NULL	
END	AS somma_controval_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO,PATRBF.RETE, PATRBF.COD_FISCALE) 
	ELSE NULL
END	AS versato_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO,PATRBF.RETE, PATRBF.COD_FISCALE) > 0 
		THEN 'n.d.'
	ELSE NULL
END	AS versato_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(MONIT.MINUS_PLUSVALENZA) OVER (PARTITION BY AREA.ID_AREA, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO,PATRBF.RETE, PATRBF.COD_FISCALE) 
	ELSE NULL
END	AS MinusPlusValenza_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN MONIT.MINUS_PLUSVALENZA IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA, PATRBF.NOME_PROGETTO, PATRBF.CHIAVE_PROGETTO,PATRBF.RETE, PATRBF.COD_FISCALE) > 0	
		THEN 'n.d.'
	ELSE NULL
END	AS MinusPlusValenza_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.VAR_PERC_PTF
	ELSE NULL
END	AS somma_var_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.COPERTURA
	ELSE NULL
END	AS somma_copertura_need_prog,
RISCHIO_AGGR_AREA.VAR_PERC_PTF AS var_needarea,
CASE 
	WHEN ISNULL(SUM(RISCHIO_AGGR_AREA.COPERTURA) OVER (PARTITION BY AREA.ID_AREA,PATRBF.RETE, PATRBF.COD_FISCALE),0.00) = 0.00 
		THEN 'n.c.' 
--------------------------------------------------------------
--INIZIO INTERVENTI OMNIA QUIII				
	WHEN TOTSELFLIQ = TOTLIQ and AREA.ID_AREA = 'LIQ' 
		THEN 'n.c.' 
--FINE INTERVENTI OMNIA QUIII
--------------------------------------------------------------			
	ELSE NULL 
END AS var_needareaString,
CAST(ISNULL(RISCHIO_AGGR_AREA.COPERTURA,100) AS DECIMAL (5,2)) AS copertura_needarea,
	CASE 
	WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) 
		--THEN '(*) Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
		THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
	ELSE '' 
END AS copertura_needareaString,
RISCHIO_AGGR_PROG.VAR_PERC_PTF AS var_need_prog,
CASE 
	WHEN ISNULL(RISCHIO_AGGR_PROG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
	ELSE NULL 
END AS var_need_progString,
RISCHIO_AGGR_PROG.COPERTURA AS copertura_need_prog,
dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) AS dataSottoscrizione, 
PATRBF.ID_CONTRATTO AS ContrattoDossier, 
--V
CASE WHEN PATRBF.TIPO_PRODOTTO <> 'CC' THEN ANAGPROD.DESCR_PRODOTTO
	 ELSE ANAGPROD.DESCR_PRODOTTO+' '+SUBSTRING(COD_CC,4,2) + '/' + SUBSTRING(COD_CC,6,LEN(ANAG_CC.COD_CC))
END AS Descrizione,
--Bido to get Code_CC field
--NOT AT ALL ANAGPROD.DESCR_PRODOTTO + ' ' + (STUFF(substring(ANAG_CC.COD_CC  , 4 , len(ANAG_CC.COD_CC) - 3), 3 , 0, '/') ) AS Descrizione,
--End Bido
--ANAGPROD.DESCR_PRODOTTO AS Descrizione,
PATRBF.CTV AS Controvalore, 
PATRBF.CTV - MONIT.MINUS_PLUSVALENZA AS VersatoNetto, 
CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 'n.d.' ELSE NULL END as VersatoNettoString,
MONIT.MINUS_PLUSVALENZA AS MinusPlusValenza, 
CASE WHEN (PATRBF.CTV - MONIT.MINUS_PLUSVALENZA) IS NULL THEN 'n.d.' ELSE NULL END as MinusPlusValenzaString,
--V nuova gestione cc
case when (patrbf.tipo_prodotto ='CC') then 0.00 
else RISCHIO_PROD.VAR_PERC_PTF
end AS VaRprodotto, 
--INIZIO INTERVENTI OMNIA
--CASE WHEN ISNULL(RISCHIO_PROD.Copertura,0.00) = 0.00 and patrbf.tipo_prodotto <>'CC' THEN 'n.c.' ELSE NULL END as varProdottoString,
CASE WHEN ISNULL(RISCHIO_PROD.Copertura,0.00) = 0.00 and patrbf.tipo_prodotto <>'CC' THEN 'n.c.' 
     WHEN patrbf.isin in('EURO00000009', 'EURO10000007') THEN 'n.c.'
ELSE NULL END as varProdottoString,
--FINE INTERVENTI OMNIA
--INIZIO INTERVENTI OMNIA
--case when (patrbf.tipo_prodotto ='CC') then 100.00
case when (patrbf.tipo_prodotto ='CC') or (patrbf.isin in('EURO00000009', 'EURO10000007')) then 100.00
--FINE INTERVENTI OMNIA
else RISCHIO_PROD.Copertura 
end AS Coperturaprodotto, 
PATRBF.REND_ANNO AS PerformanceYTD, 
PATRBF.REND_SOTTOSCRIZIONE AS performanceDS,
PARTVIA_DISINV AS partitaViaggiante,
CASE WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) THEN '*' ELSE '' END AS nota_needarea,
RISCHIO_PROD.CREDITRISK as creditrisk,
CASE
--INIZIO INTERVENTI OMNIA
--	WHEN ISNULL(RISCHIO_prod.COPERTURA,0.00) = 0.00 and patrbf.tipo_prodotto <> 'CC' THEN 'n.c.' 
	WHEN (ISNULL(RISCHIO_prod.COPERTURA,0.00) = 0.00 
	        and  patrbf.tipo_prodotto <> 'CC') 
	        or  (patrbf.isin in('EURO00000009', 'EURO10000007'))
	        THEN 'n.c.' 
--FINE INTERVENTI OMNIA	
	WHEN RISCHIO_PROD.CREDITRISK IS NULL THEN 'n.a.'
		ELSE NULL 
	END as creditriskstring,
--CASE 
--	WHEN RISCHIO_PROD.CREDITRISKEMIT IS NULL THEN 'n.a.'
--		ELSE cast(RISCHIO_PROD.CREDITRISKEMIT as varchar(20))
--	END as creditriskemit
	RISCHIO_PROD.CREDITRISKEMIT as creditriskemit
FROM 
C6MartPeriodico.PATRIMONIO_BF PATRBF
INNER JOIN 
C6MartPeriodico.ANAG_PRODOTTI ANAGPROD 
ON 
	ANAGPROD.COD_PRODOTTO = PATRBF.COD_PRODOTTO
INNER JOIN 
C6MartPeriodico.AREA_BISOGNO AREA 
ON 
	--LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA 
	(LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA and AREA.ID_AREA <>'self') or (PATRBF.ID_AREA='self' and  AREA.ID_AREA ='self')
left JOIN #TOTSELFLIQ t1 on t1.rete = PATRBF.RETE and t1.COD_FISCALE = PATRBF.COD_FISCALE
left JOIN #TOTLIQ t2 on t2.rete = PATRBF.RETE and t2.COD_FISCALE = PATRBF.COD_FISCALE
LEFT JOIN 
C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
				CASE 
					WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
						THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO+ 
						 '|' + isnull(cast(patrbf.CHIAVE_PROGETTO as varchar),'') + '|'
					when LEFT(PATRBF.ID_AREA,3)='Na' then 'RISFIN|NA|'
					ELSE 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				END
--		END + PATRBF.POSITION_ID 
		+ PATRBF.POSITION_ID 
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_PROG
	ON PATRBF.RETE= RISCHIO_AGGR_PROG.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_PROG.COD_FISCALE
	AND RISCHIO_AGGR_PROG.COD_AGGREG = 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO
		+ '|' +  isnull(cast(patrbf.CHIAVE_PROGETTO as varchar),'')
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_AREA
	ON PATRBF.RETE= RISCHIO_AGGR_AREA.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_AREA.COD_FISCALE
	AND RISCHIO_AGGR_AREA.COD_AGGREG =   case 
		when LEFT(PATRBF.ID_AREA,3) = 'Na' then 'RISFIN|NA'
         else  'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) 
		end
--	AND RISCHIO_AGGR_AREA.COD_AGGREG = 
--		CASE AREA.ID_AREA 
--			WHEN 'Na' THEN 'RISORSENONASSOCIATE' 
--			ELSE 'COMPLESSIVO|BF|' + LEFT(PATRBF.ID_AREA,3) 
--		END
LEFT JOIN
C6MartPeriodico.MONITORAGGIO_ATTUALE MONIT
ON
	PATRBF.RETE = MONIT.RETE
	AND PATRBF.COD_FISCALE = MONIT.COD_FISCALE
	AND LEFT(PATRBF.ID_AREA, 3) = MONIT.ID_AREA
	AND CASE WHEN PATRBF.NOME_PROGETTO IS NULL THEN 'XXX' ELSE PATRBF.NOME_PROGETTO END = MONIT.NOME_PROGETTO
	And patrbf.ordinamento_progetto=monit.ordinamento_progetto
--Bido to get Code_CC field
LEFT OUTER JOIN C6MartPeriodico.ANAG_CC
ON 
	ANAG_CC.COD_FISCALE = PATRBF.COD_FISCALE
	AND ANAG_CC.RETE = PATRBF.RETE
	AND cast(ANAG_CC.cod_cc as integer ) = substring(PATRBF.position_id,72,9)
WHERE 1 = 1
    AND PATRBF.CTV <>0
ORDER BY 
	AREASORTORDER,CHIAVE_PROGETTO,nome_progetto, PATRBF.CTV DESC
	drop table #TOTSELFLIQ
drop table #TOTLIQ
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S169RischiomercatoRischiocredito
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
INSERT INTO WH.PL_D2_S169RischiomercatoRischiocredito    
	SELECT  'C6MartPeriodico.PL_D2_S169RischiomercatoRischiocredito' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale,
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    PATRBF.INSTITUTENAME,
    CTV,
    M.PROFILO_ASS AS CODICEPROFILO,
    CR.MAX_VAR AS  VARMAX,
    RISK_AGG.VAR_PERC_PTF AS VAR ,
    	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END  AS VARSTRING,
    RISK_AGG.CREDITRISK  RISKCLASS,
        	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
        WHEN RISK_AGG.creditrisk is null THEN 'n.a.' 
        WHEN RISK_AGG.creditrisk = 0.00 THEN 'n.a.' 
		ELSE NULL 
	END AS  RISKCLASSSTRING,
    ISNULL(RISK_AGG.COPERTURA,0.00) AS COVERAGE,
--V La copertura viene valorizzata con un valore da 0 da 100
  --  	CASE 
	--	WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
--		ELSE 
NULL 
--	END 
AS COVERAGESTRING,
    M.RISKCLASS AS RISKCLASSMAX,
    round((SUM(CTV) OVER (PARTITION BY PATRBF.COD_FISCALE,PATRBF.RETE, PATRBF.INSTITUTENAME) / 
    -- 16.07.2011 COLAIANNI CONSOLI GESTIONE DIVISIONE PER ZERO
    CASE WHEN ( SUM(CTV) OVER (PARTITION BY PATRBF.RETE, PATRBF.COD_FISCALE) ) = 0
		 THEN 1
	     ELSE ( SUM(CTV) OVER (PARTITION BY PATRBF.RETE, PATRBF.COD_FISCALE) )
    END)		
    *100 ,2)AS PERCENTAGE,
	--V
	ORDINE,
	RISK_AGG.Ully_perc
    FROM
    (
    select 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    CASE WHEN PATRBF.RETE='F' THEN 'Patrimonio Fideuram' ELSE 'Patrimonio Sanpaolo Invest' END AS INSTITUTENAME,
    SUM(PATRBF.CTV) AS CTV,
	--V
	1 as ORDINE,
	RISK_AGG.Ully_perc
    from
    c6martperiodico.patrimonio_bf  PATRBF,C6MartPeriodico.RISCHIO_AGGREGATO RISK_AGG
    where 
    1=1
    and PATRBF.COD_FISCALE = RISK_AGG.COD_FISCALE 
    and PATRBF.rete= RISK_AGG.rete    
    and PATRBF.CTV > 0
    and
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' --or
      --RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )
    GROUP BY 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
	RISK_AGG.Ully_perc,   
    CASE WHEN PATRBF.RETE='F' THEN 'Patrimonio Fideuram' ELSE 'Patrimonio Sanpaolo Invest' END
    UNION
    SELECT 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    'Patrimonio altri Istituti' AS INSTITUTENAME,
    SUM(ROUND(TERZI.CTV,2)) AS CTV,
	--V
	2 as ORDINE,
	RISK_AGG.Ully_perc
    FROM
    c6martperiodico.PATRIMONIO_TERZI  TERZI,C6MartPeriodico.RISCHIO_AGGREGATO RISK_AGG
    where 
    1=1
    and TERZI.COD_FISCALE = RISK_AGG.COD_FISCALE 
    and TERZI.rete= RISK_AGG.rete 
    and TERZI.CTV > 0
    and
    (
      --RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' or
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )    
    GROUP BY 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    RISK_AGG.Ully_perc
    ) PATRBF
    LEFT OUTER JOIN 
    c6martperiodico.MIFID AS M
    ON 
    PATRBF.COD_FISCALE=M.COD_FISCALE
    AND PATRBF.RETE=M.RETE
	LEFT OUTER JOIN c6martperiodico.CODIFICA_RISCHIO AS CR
	ON M.PROFILO_ASS = CR.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.CODIFICA_CREDITRISK  CK
    ON 
    M.riskclass=CK.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.RISCHIO_AGGREGATO  RISK_AGG
    ON 
    PATRBF.COD_FISCALE=RISK_AGG.COD_FISCALE
    AND PATRBF.RETE=RISK_AGG.RETE
    AND 
    (case when  RISK_AGG.COD_AGGREG = 'COMPLESSIVO|BF' and PATRBF.RETE= 'F'  then 'Patrimonio Fideuram' 
          WHEN  RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' and PATRBF.RETE= 'S'  then 'Patrimonio Sanpaolo Invest'
          else 'Patrimonio altri Istituti' end)= PATRBF.INSTITUTENAME
   where
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' or
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )
    UNION ALL
    SELECT  'C6MartPeriodico.PL_D2_S169RischiomercatoRischiocredito' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale, 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    'Patrimonio Complessivo' AS INSTITUTENAME,
    SUM(CTV),
    MAX(M.PROFILO_ASS) AS CODICEPROFILO,
    MAX(CR.MAX_VAR) AS  VARMAX,
    MAX(RISK_AGG.VAR_PERC_PTF) AS VAR ,
    MAX(	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END) AS VARSTRING,
    MAX(RISK_AGG.CREDITRISK)  RISKCLASS,
    MAX(
         	case	WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
        WHEN RISK_AGG.creditrisk is null THEN 'n.a.' 
        WHEN RISK_AGG.creditrisk = 0.00 THEN 'n.a.' 
		ELSE NULL 
	END )
      AS  RISKCLASSSTRING,
    MAX(ISNULL(RISK_AGG.COPERTURA,0.00)) AS COVERAGE,
    MAX(   	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END) AS COVERAGESTRING,
    --MAX(CK.DESCRIZIONE) AS RISKCLASSMAX,
	MAX(M.RISKCLASS) AS RISKCLASSMAX,
    100 AS PERCENTAGE,
	--V
	3 AS ORDINE,
	RISK_AGG.Ully_perc
    FROM
    (
    select 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    SUM(PATRBF.CTV) AS CTV
    from
    c6martperiodico.patrimonio_bf  PATRBF
    where 
    1=1 
	and PATRBF.CTV > 0    
    GROUP BY 
    PATRBF.RETE,
    PATRBF.COD_FISCALE
    UNION
    SELECT 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    SUM(ROUND(TERZI.CTV,2)) AS CTV
    FROM
    c6martperiodico.PATRIMONIO_TERZI  TERZI
        where 
    1=1 
	and TERZI.CTV > 0       
     GROUP BY 
    TERZI.RETE,
    TERZI.COD_FISCALE
    ) PATRBF
    LEFT OUTER JOIN 
    c6martperiodico.MIFID AS M
    ON 
    PATRBF.COD_FISCALE=M.COD_FISCALE
    AND PATRBF.RETE=M.RETE
	LEFT OUTER JOIN c6martperiodico.CODIFICA_RISCHIO AS CR
	ON M.PROFILO_ASS = CR.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.CODIFICA_CREDITRISK  CK
    ON 
      M.riskclass=CK.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.RISCHIO_AGGREGATO  RISK_AGG
    ON 
    PATRBF.COD_FISCALE=RISK_AGG.COD_FISCALE
    AND PATRBF.RETE=RISK_AGG.RETE
        where  
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO'
    )
    GROUP BY 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    RISK_AGG.Ully_perc
	--V
	order by ordine
END
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S170RischioDiversificazione
BEGIN
INSERT INTO WH.PL_D2_S170RischioDiversificazione    
	SELECT  'C6MartPeriodico.PL_D2_S170RischioDiversificazione' as ProcedureName, K.RETE as i_rete, K.COD_FISCALE as i_codiceFiscale, 
K.COD_FISCALE,
K.RETE,
CASE 
	when cod_Aggreg = 'COMPLESSIVO|BF' then (SELECT isnull(sum(ctv),0) FROM  c6martperiodico.patrimonio_bf  			
			where cod_fiscale = K.COD_FISCALE
				  and rete= K.RETE 
				  and CTV > 0)
	when cod_Aggreg = 'COMPLESSIVO|TERZI' then (SELECT isnull(sum(ctv),0) FROM  c6martperiodico.patrimonio_terzi  			
			where cod_fiscale = K.COD_FISCALE
				  and rete= K.RETE  
				  and CTV > 0)
	when cod_Aggreg = 'COMPLESSIVO' then (SELECT isnull(sum(ctv),0) FROM  c6martperiodico.patrimonio_bf  			
			where cod_fiscale = K.COD_FISCALE
				  and rete= K.RETE 
				  and CTV > 0) + (SELECT isnull(sum(ctv),0) FROM  c6martperiodico.patrimonio_terzi  			
			where cod_fiscale = K.COD_FISCALE
				  and rete= K.RETE  
				  and CTV > 0)
	else 0
END AS CTV_AGGREG,	
K.CREDITRISK,
CASE 
	WHEN ((select count(*)
	from c6martperiodico.patrimonio_Bf
	where cod_fiscale = K.COD_FISCALE and rete = K.RETE) - (select count(*)
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' and cod_fiscale = K.COD_FISCALE and rete = K.RETE) = 0) THEN 0
	ELSE VAR_PERC_PTF 
END AS VAR,
CASE WHEN ISNULL(COPERTURA,0.00) = 0.00 AND (select count(*)
	from c6martperiodico.patrimonio_Bf
	where cod_fiscale = K.COD_FISCALE and rete = K.RETE) - (select count(*)
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' and cod_fiscale = K.COD_FISCALE and rete = K.RETE) <> 0 THEN 'n.c.' ELSE NULL END as varString,
CASE 
	WHEN (ISNULL(copertura,100) < 100) AND (select count(*)
	from c6martperiodico.patrimonio_Bf
	where cod_fiscale = K.COD_FISCALE and rete = K.RETE) - (select count(*)
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' and cod_fiscale = K.COD_FISCALE and rete = K.RETE) <> 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 ((select count(*)
	from c6martperiodico.patrimonio_Bf
	where cod_fiscale = K.COD_FISCALE and rete = K.RETE) - (select count(*)
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' and cod_fiscale = K.COD_FISCALE and rete = K.RETE) = 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')
ORDER BY ordine
END 
-------------------------------------------------------------------------
-------------------------------------------PL_D2_S171PatrimonioNonRappresentabileAssettClass
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 INSERT INTO WH.PL_D2_S171PatrimonioNonRappresentabileAssettClass    
	  SELECT 'C6MartPeriodico.PL_D2_S171PatrimonioNonRappresentabileAssettClass' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale, 
		PATRBF.ID_CONTRATTO as Contratto,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) as DataSottoscrizione,
		ANAGP.DESCR_PRODOTTO AS Descrizione,
		PATRBF.CTV as Controvalore,
		PATRBF.CTV as controvalore_contratto,
		PATRBF.PARTVIA_DISINV as PartitaViaggiante,
		CASE PATRBF.RETE WHEN 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' end as Intermediario
	FROM C6MARTPERIODICO.PATRIMONIO_BF PATRBF
	INNER JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAGP
		ON PATRBF.COD_PRODOTTO = ANAGP.COD_PRODOTTO
	LEFT OUTER JOIN C6MARTPERIODICO.ASSET_PERC ASSETPERC 
		ON PATRBF.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
		AND ASSETPERC.LIVELLO = 1
	WHERE 1 = 1
		AND PATRBF.TIPO_PRODOTTO <> 'ASUL'
		AND ASSETPERC.COD_PRODOTTO IS NULL
--INIZIO INTERVENTI OMNIA		
        AND PATRBF.CTV <> 0.00
--INIZIO INTERVENTI OMNIA		
	UNION ALL
	  SELECT 'C6MartPeriodico.PL_D2_S171PatrimonioNonRappresentabileAssettClass' as ProcedureName, PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceFiscale,  
		PATRBF.ID_CONTRATTO as Contratto,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) as DataSottoscrizione,
		ANAGP.DESCR_PRODOTTO AS Descrizione,
		SUM(ASUL.CTV) as Controvalore,
		MAX(PATRBF.CTV) as controvalore_contratto,
		SUM(PATRBF.PARTVIA_DISINV) as PartitaViaggiante,
		CASE PATRBF.RETE WHEN 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' end as Intermediario
	FROM C6MARTPERIODICO.PATRIMONIO_BF PATRBF
	INNER JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAGP
		ON PATRBF.COD_PRODOTTO = ANAGP.COD_PRODOTTO
	INNER JOIN C6MARTPERIODICO.DETTAGLIO_ASUL ASUL
		ON PATRBF.RETE = ASUL.RETE
		AND PATRBF.COD_FISCALE = ASUL.COD_FISCALE
		AND PATRBF.ID_CONTRATTO = ASUL.ID_CONTRATTO
	LEFT OUTER JOIN C6MARTPERIODICO.ASSET_PERC ASSETPERC
		ON ASSETPERC.COD_PRODOTTO = ASUL.COD_PRODOTTO
		AND ASSETPERC.LIVELLO = 1 
	WHERE 1 = 1
		AND PATRBF.TIPO_PRODOTTO = 'ASUL'
		AND ASSETPERC.COD_PRODOTTO IS NULL
        GROUP BY 
        PATRBF.ID_CONTRATTO,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) ,
		ANAGP.DESCR_PRODOTTO,
		PATRBF.RETE,
		PATRBF.COD_FISCALE
	ORDER BY CONTROVALORE DESC
END
-------------------------------------------------------------------------
-------------------------------------------PL_MP_S137Bonus
BEGIN  
INSERT INTO WH.PL_MP_S137Bonus    
	  SELECT 'C6MartPeriodico.PL_MP_S137Bonus' as ProcedureName, [RETE] as i_rete, [COD_FISCALE] as i_codiceF,
			[RETE],
			bonus.[COD_FISCALE], 
			[DES_PROD] = CASE
				WHEN desrc.descrizione is null THEN ''								 
				ELSE desrc.descrizione  		                   	
            END, 
            bonus.[COD_CONF],           
            bonus.[CTV],
			bonus.[DT_TRIM],		
			'Bonus Maturato'  as [DESBONUS_M],
			bonus.[BONUS_M],
			bonus.[DTDEC_M],	
			'Bonus a scadenza 5 anni'	as [DESBONUS_5],
			bonus.[BONUS_5],
			bonus.[DTDEC_5],	
			'Bonus a scadenza 10 anni'	as [DESBONUS_10],
			bonus.[BONUS_10],
			bonus.[DTDEC_10],			
            bonus.[COD_PROD]			
	FROM [C6MartPeriodico].[BONUS] bonus
	Left Join c6martperiodico.descrizione_bonus  desrc
	on desrc.cod_prod = bonus.cod_prod
END
-------------------------------------------------------------------------
-------------------------------------------PL_MP_S135MonitoraggioInvestimento
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
INSERT INTO WH.PL_MP_S135MonitoraggioInvestimento    
	  SELECT 'C6MartPeriodico.PL_MP_S135MonitoraggioInvestimento' as ProcedureName, [RETE] as i_rete, [COD_FISCALE] as i_codiceF,
		ID_AREA AS NEED_AREA,
		CASE
			WHEN NOME_PROGETTO = 'XXX' THEN ''
			ELSE LTRIM(RTRIM(NOME_PROGETTO))
		END AS NOME_PROGETTO,
		ordinamento_progetto,
		DATA_ATTIVAZIONE AS DATAVALORIZZAZIONE,
		APPORTO_INIZIALE AS CONTROVALORE,
		APPORTO_INIZIALE  AS RISORSEASSOCIATE
	FROM C6MartPeriodico.MONITORAGGIO_ATTUALE
	UNION
	SELECT 'C6MartPeriodico.PL_MP_S135MonitoraggioInvestimento' as ProcedureName, [RETE] as i_rete, [COD_FISCALE] as i_codiceF,
		ID_AREA,
		CASE
			WHEN NOME_PROGETTO = 'XXX' THEN ''
			ELSE LTRIM(RTRIM(NOME_PROGETTO))
		END AS NOME_PROGETTO,
		ordinamento_progetto,
		DATA_CTV,
		CTV_MONITORATO,
		ISNULL (RISORSE_ASSOCIATE, 0) -- ISNULL(CEDOLE_DIV, 0)
	FROM C6MartPeriodico.MONITORAGGIO_STORICO
	ORDER BY NEED_AREA, NOME_PROGETTO, DATAVALORIZZAZIONE
END
-------------------------------------------------------------------------
-------------------------------------------PL_MP_S134MonitoraggioLiquidita
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
-- DECLARE @RendimNonRappr BIT
INSERT INTO WH.PL_MP_S134MonitoraggioLiquidita    
	  SELECT 'C6MartPeriodico.PL_MP_S134MonitoraggioLiquidita' as ProcedureName, MONIT.RETE as i_rete, MONIT.COD_FISCALE as i_codiceF,
		case when RENDIMNONRAPPR=1 then 1 else 0 end AS cf_rendim_non_rappr,
		MONIT.id_Area AS Need_Area,
		CASE
			WHEN MONIT.NOME_PROGETTO = 'XXX' THEN ''
			ELSE LTRIM(RTRIM(MONIT.NOME_PROGETTO))
		END AS Nome_Progetto,
		monit.ordinamento_progetto,
		dbo.TOSHORTDATESTRING(DATA_ATTIVAZIONE) AS DataAttivazioneMonitoraggio,
		CTV_MONITORATO AS ControvaloreMonitorato,
		APPORTO_INIZIALE AS ApportoIniziale,
		APPORTO_SUCCESSIVO AS ApportoSuccessivo,
		LIQUIDAZIONI,
		CEDOLE_DIVIDENDI AS CedoleEDividendi,
		MINUS_PLUSVALENZA AS MinusPlusAreaProgetto,
		RENDIMENTO_CUMULATO AS Rendimento_Attuale,
		RISORSE_ASSOCIATE AS RisorseApportate,
		dbo.TOSHORTDATESTRING(DATA_CTV) AS DataControvalore,
		RENDIMENTO_ANNUALIZZATO
	FROM
		C6MartPeriodico.MONITORAGGIO_ATTUALE MONIT
        LEFT OUTER JOIN
        (
            SELECT
			PATR_BF.ID_AREA,
            PATR_BF.COD_FISCALE,
            PATR_BF.RETE,
			CASE
			WHEN PATR_BF.NOME_PROGETTO = 'XXX' THEN ''
			ELSE NOME_PROGETTO end as NOME_PROGETTO,
			patr_bf.ordinamento_progetto,
            1 as RENDIMNONRAPPR
		FROM
			C6MartPeriodico.PATRIMONIO_BF AS PATR_BF
			LEFT OUTER JOIN C6MartPeriodico.AREA_BISOGNO AS AREA ON
				PATR_BF.ID_AREA = AREA.ID_AREA
		WHERE
			 PATR_BF.REND_NON_RAPPR = 1
          group by  
          	PATR_BF.ID_AREA,
            PATR_BF.COD_FISCALE,
            PATR_BF.RETE,
			CASE
			WHEN PATR_BF.NOME_PROGETTO = 'XXX' THEN ''
			ELSE NOME_PROGETTO end,
			patr_bf.ordinamento_progetto
         ) PATR_BF 
         ON PATR_BF.COD_FISCALE=MONIT.COD_FISCALE
            AND PATR_BF.RETE= MONIT.RETE
            AND left(PATR_BF.ID_AREA,3)=left(MONIT.ID_AREA,3)
            AND  isnull(PATR_BF.NOME_PROGETTO,'XXX')=isnull(MONIT.NOME_PROGETTO,'XXX')
			And monit.ordinamento_progetto=patr_bf.ordinamento_progetto
END
-------------------------------------------------------------------------
-------------------------------------------PL_MP_S134BISMonitoraggioLiqInv
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
INSERT INTO WH.PL_MP_S134BISMonitoraggioLiqInv  
	SELECT 'C6MartPeriodico.PL_MP_S134BISMonitoraggioLiqInv' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceF,
		ID_AREA AS NEED_AREA,
		CASE
			WHEN NOME_PROGETTO = 'XXX' THEN ''
			ELSE LTRIM(RTRIM(NOME_PROGETTO))
		END AS NOME_PROGETTO,
		ordinamento_progetto,
		DATA_ATTIVAZIONE AS DATAVALORIZZAZIONE,
		APPORTO_INIZIALE AS CONTROVALORE,
		APPORTO_INIZIALE  AS RISORSEASSOCIATE
	FROM C6MartPeriodico.MONITORAGGIO_ATTUALE
	UNION
	SELECT 'C6MartPeriodico.PL_MP_S134BISMonitoraggioLiqInv' as ProcedureName, RETE as i_rete, COD_FISCALE as i_codiceF,
		ID_AREA,
		CASE
			WHEN NOME_PROGETTO = 'XXX' THEN ''
			ELSE LTRIM(RTRIM(NOME_PROGETTO))
		END AS NOME_PROGETTO,
		ordinamento_progetto,
		DATA_CTV,
		CTV_MONITORATO,
		ISNULL (RISORSE_ASSOCIATE, 0) -- ISNULL(CEDOLE_DIV, 0)
	FROM C6MartPeriodico.MONITORAGGIO_STORICO
	ORDER BY NEED_AREA, NOME_PROGETTO, DATAVALORIZZAZIONE
END
-------------------------------------------------------------------------
-------------------------------------------PL_MP_S133BISPrincipaliProdotti
BEGIN	
;with ata as
(
SELECT PATRBF.RETE as i_rete, PATRBF.COD_FISCALE as i_codiceF, 
             ANAGPROD.DESCR_PRODOTTO AS descrProdotto
             ,PATRBF.CTV AS Controvalore
             ,CASE 
                    WHEN patrbf.tipo_prodotto = 'CC' THEN 0.00 
                    ELSE RISCHIO_PROD.VAR_PERC_PTF
             END AS VaRprodotto
             ,((CASE 
                      WHEN ((PATRBF.CTV * RISCHIO_PROD.VAR_PERC_PTF)/100) is null then 0.00 
                      ELSE(PATRBF.CTV * RISCHIO_PROD.VAR_PERC_PTF)/100 
                END) /    (CASE
                                    WHEN  sum((PATRBF.CTV * isnull(RISCHIO_PROD.VAR_PERC_PTF,0))/100) over (partition by 'totale'+PATRBF.RETE+PATRBF.COD_FISCALE) = 0 THEN 1
                                    ELSE  sum((PATRBF.CTV * isnull(RISCHIO_PROD.VAR_PERC_PTF,0))/100) over (partition by 'totale'+PATRBF.RETE+PATRBF.COD_FISCALE)
                                 END))*100 as rischioRelativo    
             ,(PATRBF.CTV/(sum(PATRBF.CTV) over (partition by 'totale'+PATRBF.RETE+PATRBF.COD_FISCALE)))*100  AS pesoRelativo
             ,PATRBF.ID_AREA  AS codAreaBisogno
       FROM C6MartPeriodico.PATRIMONIO_BF PATRBF
       INNER JOIN C6MartPeriodico.ANAG_PRODOTTI ANAGPROD 
             ON ANAGPROD.COD_PRODOTTO = PATRBF.COD_PRODOTTO
       INNER JOIN C6MartPeriodico.AREA_BISOGNO AREA 
             ON LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA 
       LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_PROD 
             ON PATRBF.RETE= RISCHIO_PROD.RETE
             AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
             AND RISCHIO_PROD.COD_AGGREG = CASE 
                                                                    WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
                                                                         THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO+ 
                                                                          '|' + isnull(cast(patrbf.ordinamento_progetto as varchar),'') + '|'
                                                                   WHEN LEFT(PATRBF.ID_AREA,3)='Na' then 'RISFIN|NA|'
                                                                   ELSE 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
                                                               END
                                                               + PATRBF.POSITION_ID 
       WHERE 
    PATRBF.CTV <>0
       AND PATRBF.ID_AREA <> 'Cc'
       ), tot as
       (select *, row_number() over (partition by i_rete, i_codiceF ORDER BY rischioRelativo DESC, Controvalore DESC) as pos
         from ata
         )
		 INSERT INTO WH.PL_MP_S133BISPrincipaliProdotti  
		SELECT 'C6MartPeriodico.PL_MP_S133BISPrincipaliProdotti' as ProcedureName, i_rete, i_codiceF, descrProdotto, Controvalore, VaRprodotto, 
																	rischioRelativo, pesoRelativo, codAreaBisogno from tot where pos <=10
END
-------------------------------------------------------------------------
----[C6MartPeriodico].[PL_MP_S133AreeBisognoPrincProd]
BEGIN
INSERT INTO wh.[PL_MP_S133AreeBisognoPrincProd]
SELECT 'PL_MP_S133AreeBisognoPrincProd', [Rete]
		,[CodiceFiscale]
		,[NeedArea]
      ,[AreaName]
      ,[PercentualeModello]
      ,[PercentualeAttuale]
      ,[ControvaloreAttuale]
      ,[ControvaloreModello]
      ,[Totale_Percentuale]
      ,[DifferenzaEuro]
      ,[DifferenzaPercentuale]
      ,[var_needarea]
      ,[var_needareaString]
      ,[copertura_needarea]
      ,[copertura_needareaString]
      ,[Nota]
      ,[somma_controvalAttuale]
      ,[somma_controvalModello]
      ,[somma_percentualeAttuale]
      ,[somma_percentualeModello]
      ,[var_tot]
      ,[var_totString]
      ,[var_tot_pir]
      ,[var_tot_pirString]
      ,[copertura_tot]
      ,[copertura_totString]
      ,[copertura_tot_pir]
      ,[copertura_tot_pirString]
      ,[VAR_RISFIN]
      ,[VAR_RISFINSTRING]
      ,[copertura_risfin]
      ,[copertura_risfinString]
      ,[ordinamento]
  FROM [C6MartPeriodico].[TB_S133_S157DatiPiramide]
  order by ordinamento
END
-------------------------------------------------------------------------
------ [C6MartPeriodico].[PL_MP_S146RischioDiversificazione]
begin
	select count(*) as contaCC, cod_fiscale, rete
	into #contaCC
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' 
	group by cod_fiscale, rete
	select count(*) as contaPOS, cod_fiscale, rete
	into #contaPOS
	from c6martperiodico.patrimonio_Bf
	group by cod_fiscale, rete
INSERT INTO wh.PL_MP_S146RischioDiversificazione
SELECT 'PL_MP_S146RischioDiversificazione',K.RETE, K.COD_FISCALE,
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
left join #contaCC cc on K.COD_FISCALE = cc.COD_FISCALE and K.RETE = cc.rete
left join #contaPOS pos on K.COD_FISCALE = pos.COD_FISCALE and K.RETE = pos.rete
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')
ORDER BY Ordine
END 
-------------------------------------------------------------------------
---------[C6MartPeriodico].[PL_MP_S141AnalisiRisparmioTable]
begin 
select sum(ctv_prodotto) as patr_compl, rete, cod_fiscale 
into #patr_compl
from c6martperiodico.patrimonio_emittenti 
where ctv_prodotto > 0
group by  rete, cod_fiscale 
INSERT INTO wh.PL_MP_S141AnalisiRisparmioTable
SELECT  'PL_MP_S141AnalisiRisparmioTable',RETE, COD_FISCALE,
	COD_FISCALE,
	RETE,
	RATING_AAA,
	RATING_AAp,
	RATING_AA,
	RATING_AAm,
	RATING_Ap,
	RATING_A,
	RATING_Am,
	RATING_BBBp,
	RATING_BBB,
	RATING_BBBm,
	RATING_BBp,
	RATING_BB,
	RATING_BBm,
	RATING_Bp,
	RATING_B,
	RATING_Bm,
	RATING_CCCp,
	RATING_CCC,
	RATING_CCCm,
	RATING_CC,
	RATING_C,
	RATING_D,
	RATING_na,
	FLG_RISKCLASS1,
	FLG_RISKCLASS2,
	FLG_RISKCLASS3,
	FLG_RISKCLASS4,
	FLG_RISKCLASS5,
	FLG_RISKCLASS6,
	FLG_RISKCLASS7,
	FLG_RISKCLASS8,
	FLG_RISKCLASS9,
	FLG_RISKCLASS10,
	INTERMEDIARIO,
	ISSUER,
	STOCKSCounterValue,
	bondsCounterValue,
	CONCENTRATION_ISSUER,
	CONCENTRATION,
	NC 
FROM  (
-- PER INTERMEDIARIO 
    SELECT
		COD_FISCALE,
		RETE,
		MAX(RATING_AAA) AS RATING_AAA,
		MAX(RATING_AAp) AS RATING_AAp,
		MAX(RATING_AA) AS RATING_AA,
		MAX(RATING_AAm) AS RATING_AAm,
		MAX(RATING_Ap) AS RATING_Ap,
		MAX(RATING_A) AS RATING_A,
		MAX(RATING_Am) AS RATING_Am,
		MAX(RATING_BBBp) AS RATING_BBBp,
		MAX(RATING_BBB) AS RATING_BBB,
		MAX(RATING_BBBm) AS RATING_BBBm,
		MAX(RATING_BBp) AS RATING_BBp,
		MAX(RATING_BB) AS RATING_BB,
		MAX(RATING_BBm) AS RATING_BBm,
		MAX(RATING_Bp) AS RATING_Bp,
		MAX(RATING_B) AS RATING_B,
		MAX(RATING_Bm) AS RATING_Bm,
		MAX(RATING_CCCp) AS RATING_CCCp,
		MAX(RATING_CCC) AS RATING_CCC,
		MAX(RATING_CCCm) AS RATING_CCCm,
		MAX(RATING_CC) AS RATING_CC,
		MAX(RATING_C) AS RATING_C,
		MAX(RATING_D) AS RATING_D,
		MAX(RATING_na) AS RATING_na,
		MAX(FLG_RISKCLASS1) AS FLG_RISKCLASS1,
		MAX(FLG_RISKCLASS2) AS FLG_RISKCLASS2,
		MAX(FLG_RISKCLASS3) AS FLG_RISKCLASS3,
		MAX(FLG_RISKCLASS4) AS FLG_RISKCLASS4,
		MAX(FLG_RISKCLASS5) AS FLG_RISKCLASS5,
		MAX(FLG_RISKCLASS6) AS FLG_RISKCLASS6,
		MAX(FLG_RISKCLASS7) AS FLG_RISKCLASS7,
		MAX(FLG_RISKCLASS8) AS FLG_RISKCLASS8,
		MAX(FLG_RISKCLASS9) AS FLG_RISKCLASS9,
		MAX(FLG_RISKCLASS10) AS FLG_RISKCLASS10,
		--V nel caso sia null è BF???
		isnull(INTERMEDIARIO,'BF') AS INTERMEDIARIO,
		EMITTENTE AS ISSUER,
		--RATING AS RATING, 
		SUM(STOCKSCounterValue) AS  STOCKSCounterValue,
		sum(bondsCounterValue) AS bondsCounterValue,
		0 as  CONCENTRATION_ISSUER ,
		--V normalizzo la percentuale per essere rappresentato sul report
		MAX(CONCENTRATION)* 100 AS CONCENTRATION,
--EN 26012016: solo se per un emittente nessun prodotto riporta nessuna copertura
--             viene impostato nc=1 (non classificato) e si assume che nessuna riskclass
--             sia valorizzato.
--		sum(case when copertura > 0 then 0 else 1 end) as nc
		min(case when copertura > 0 then 0 else 1 end) as nc
	FROM
				(SELECT --Y.*   
					V.COD_FISCALE,
					V.RETE,
					INTERMEDIARIO,
					CREDITRISKCLASS,
					EMITTENTE,
					--RATING AS RATING,                  
					CASE WHEN RATING = 'AAA' THEN 1 ELSE 0 END AS RATING_AAA,
					CASE WHEN RATING = 'AA+' THEN 1 ELSE 0 END AS RATING_AAp,
					CASE WHEN RATING = 'AA' THEN 1 ELSE 0 END AS RATING_AA,
					CASE WHEN RATING = 'AA-' THEN 1 ELSE 0 END AS RATING_AAm,
					CASE WHEN RATING = 'A+' THEN 1 ELSE 0 END AS RATING_Ap,
					CASE WHEN RATING = 'A' THEN 1 ELSE 0 END AS RATING_A,
					CASE WHEN RATING = 'A-' THEN 1 ELSE 0 END AS RATING_Am,
					CASE WHEN RATING = 'BBB+' THEN 1 ELSE 0 END AS RATING_BBBp,
					CASE WHEN RATING = 'BBB' THEN 1 ELSE 0 END AS RATING_BBB,
					CASE WHEN RATING = 'BBB-' THEN 1 ELSE 0 END AS RATING_BBBm,
					CASE WHEN RATING = 'BB+' THEN 1 ELSE 0 END AS RATING_BBp,
					CASE WHEN RATING = 'BB' THEN 1 ELSE 0 END AS RATING_BB,
					CASE WHEN RATING = 'BB-' THEN 1 ELSE 0 END AS RATING_BBm,
					CASE WHEN RATING = 'B+' THEN 1 ELSE 0 END AS RATING_Bp,
					CASE WHEN RATING = 'B' THEN 1 ELSE 0 END AS RATING_B,
					CASE WHEN RATING = 'B-' THEN 1 ELSE 0 END AS RATING_Bm,
					CASE WHEN RATING = 'CCC+' THEN 1 ELSE 0 END AS RATING_CCCp,
					CASE WHEN RATING = 'CCC' THEN 1 ELSE 0 END AS RATING_CCC,
					CASE WHEN RATING = 'CCC-' THEN 1 ELSE 0 END AS RATING_CCCm,
					CASE WHEN RATING = 'CC' THEN 1 ELSE 0 END AS RATING_CC,
					CASE WHEN RATING = 'C' THEN 1 ELSE 0 END AS RATING_C,
					CASE WHEN RATING = 'D' THEN 1 ELSE 0 END AS RATING_D,
					CASE WHEN RATING is null THEN 1 ELSE 0 END AS RATING_na,                
					CASE WHEN CREDITRISKCLASS ='Rischio 1/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS1,
					CASE WHEN CREDITRISKCLASS ='Rischio 2/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS2,
					CASE WHEN CREDITRISKCLASS ='Rischio 3/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS3,
					CASE WHEN CREDITRISKCLASS ='Rischio 4/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS4,
					CASE WHEN CREDITRISKCLASS ='Rischio 5/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS5,
					CASE WHEN CREDITRISKCLASS ='Rischio 6/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS6,
					CASE WHEN CREDITRISKCLASS ='Rischio 7/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS7,
					CASE WHEN CREDITRISKCLASS ='Rischio 8/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS8,
					CASE WHEN CREDITRISKCLASS ='Rischio 9/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS9,
					CASE WHEN CREDITRISKCLASS ='Rischio 10/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS10,
					SUM(CTV_AZ_OB_EMIT) as CTV_AZ_OB_EMIT,
					SUM(CTV_PRODOTTO) AS CTV_PRODOTTO,
					sum(CTV_AZIONARIO) AS STOCKSCounterValue,
					sum(CTV_OBBLIGAZIONARIO) AS bondsCounterValue,
					0 AS  CONCENTRATION_ISSUER ,
					SUM(CTV_AZ_OB_EMIT_INTER)/SUM(CTV_COMPL_NOCC_NEG)  AS CONCENTRATION,
					sum(copertura) as copertura
				FROM  C6MARTPERIODICO.PATRIMONIO_EMITTENTI V  
					LEFT JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAG
					ON V.COD_PRODOTTO = ANAG.COD_PRODOTTO
				WHERE 1=1
					AND (CTV_AZIONARIO >0 OR CTV_OBBLIGAZIONARIO > 0)
				GROUP BY
					V.COD_FISCALE,
					V.RETE,
					INTERMEDIARIO,
					EMITTENTE,
					RATING,
					CREDITRISKCLASS 
				 ) Y
	GROUP BY 
		 COD_FISCALE,
		 RETE,
		 INTERMEDIARIO,
		 EMITTENTE
--V devo rappresentare solo le 3 principali me le ordine e nel codice scorro per le prime 3 dopo aver filtrato per intermediario
--ORDER BY CONCENTRATION DESC
UNION 
------COMPLESSIVO
   SELECT
     l.COD_FISCALE,
     l.RETE,
     MAX(RATING_AAA) AS RATING_AAA,
		MAX(RATING_AAp) AS RATING_AAp,
		MAX(RATING_AA) AS RATING_AA,
		MAX(RATING_AAm) AS RATING_AAm,
		MAX(RATING_Ap) AS RATING_Ap,
		MAX(RATING_A) AS RATING_A,
		MAX(RATING_Am) AS RATING_Am,
		MAX(RATING_BBBp) AS RATING_BBBp,
		MAX(RATING_BBB) AS RATING_BBB,
		MAX(RATING_BBBm) AS RATING_BBBm,
		MAX(RATING_BBp) AS RATING_BBp,
		MAX(RATING_BB) AS RATING_BB,
		MAX(RATING_BBm) AS RATING_BBm,
		MAX(RATING_Bp) AS RATING_Bp,
		MAX(RATING_B) AS RATING_B,
		MAX(RATING_Bm) AS RATING_Bm,
		MAX(RATING_CCCp) AS RATING_CCCp,
		MAX(RATING_CCC) AS RATING_CCC,
		MAX(RATING_CCCm) AS RATING_CCCm,
		MAX(RATING_CC) AS RATING_CC,
		MAX(RATING_C) AS RATING_C,
		MAX(RATING_D) AS RATING_D,
		MAX(RATING_na) AS RATING_na,
     MAX(FLG_RISKCLASS1) AS FLG_RISKCLASS1,
     MAX(FLG_RISKCLASS2) AS FLG_RISKCLASS2,
     MAX(FLG_RISKCLASS3) AS FLG_RISKCLASS3,
     MAX(FLG_RISKCLASS4) AS FLG_RISKCLASS4,
	 MAX(FLG_RISKCLASS5) AS FLG_RISKCLASS5,
	 MAX(FLG_RISKCLASS6) AS FLG_RISKCLASS6,
	 MAX(FLG_RISKCLASS7) AS FLG_RISKCLASS7,
	 MAX(FLG_RISKCLASS8) AS FLG_RISKCLASS8,
	 MAX(FLG_RISKCLASS9) AS FLG_RISKCLASS9,
	 MAX(FLG_RISKCLASS10) AS FLG_RISKCLASS10,
	 isnull(INTERMEDIARIO,'BF') AS INTERMEDIARIO,
     EMITTENTE AS ISSUER,
     SUM(STOCKSCounterValue) AS  STOCKSCounterValue,
     SUM(bondsCounterValue) AS bondsCounterValue,
     SUM(isnull(bondsCounterValue,0)+ isnull(STOCKSCounterValue,0))/ max(p.patr_compl)  *100  CONCENTRATION_ISSUER ,
     0 AS CONCENTRATION,
--EN 26012016
--	sum(case when copertura > 0 then 0 else 1 end) as nc
	min(case when copertura > 0 then 0 else 1 end) as nc
FROM
(
SELECT  --L.*
	y.COD_FISCALE,
	y.RETE,
	'COMPLESSIVO' as INTERMEDIARIO,
	CREDITRISKCLASS,
	EMITTENTE,
	RATING_AAA,
	RATING_AAp,
	RATING_AA,
	RATING_AAm,
	RATING_Ap,
	RATING_A,
	RATING_Am,
	RATING_BBBp,
	RATING_BBB,
	RATING_BBBm,
	RATING_BBp,
	RATING_BB,
	RATING_BBm,
	RATING_Bp,
	RATING_B,
	RATING_Bm,
	RATING_CCCp,
	RATING_CCC,
	RATING_CCCm,
	RATING_CC,
	RATING_C,
	RATING_D,
	RATING_na,
	FLG_RISKCLASS1,
	FLG_RISKCLASS2,
	FLG_RISKCLASS3,
	FLG_RISKCLASS4,
	FLG_RISKCLASS5,
	FLG_RISKCLASS6,
	FLG_RISKCLASS7,
	FLG_RISKCLASS8,
	FLG_RISKCLASS9,
	FLG_RISKCLASS10,
	SUM(CTV_AZ_OB_EMIT) CTV_AZ_OB_EMIT,
	SUM(STOCKSCounterValue) AS STOCKSCounterValue,
	SUM(bondsCounterValue) AS bondsCounterValue,
	0 AS CONCENTRATION_ISSUER,
	SUM(CTV_AZ_OB_EMIT_INTER)/SUM(CTV_COMPLessivo) TOT ,
	SUM(COPERTURA) AS COPERTURA
FROM
(
		SELECT --V.*     
			V.COD_FISCALE,
			V.RETE,
			'COMPLESSIVO' as INTERMEDIARIO,
			CREDITRISKCLASS,
			EMITTENTE,            
			CASE WHEN RATING = 'AAA' THEN 1 ELSE 0 END AS RATING_AAA,
			CASE WHEN RATING = 'AA+' THEN 1 ELSE 0 END AS RATING_AAp,
			CASE WHEN RATING = 'AA' THEN 1 ELSE 0 END AS RATING_AA,
			CASE WHEN RATING = 'AA-' THEN 1 ELSE 0 END AS RATING_AAm,
			CASE WHEN RATING = 'A+' THEN 1 ELSE 0 END AS RATING_Ap,
			CASE WHEN RATING = 'A' THEN 1 ELSE 0 END AS RATING_A,
			CASE WHEN RATING = 'A-' THEN 1 ELSE 0 END AS RATING_Am,
			CASE WHEN RATING = 'BBB+' THEN 1 ELSE 0 END AS RATING_BBBp,
			CASE WHEN RATING = 'BBB' THEN 1 ELSE 0 END AS RATING_BBB,
			CASE WHEN RATING = 'BBB-' THEN 1 ELSE 0 END AS RATING_BBBm,
			CASE WHEN RATING = 'BB+' THEN 1 ELSE 0 END AS RATING_BBp,
			CASE WHEN RATING = 'BB' THEN 1 ELSE 0 END AS RATING_BB,
			CASE WHEN RATING = 'BB-' THEN 1 ELSE 0 END AS RATING_BBm,
			CASE WHEN RATING = 'B+' THEN 1 ELSE 0 END AS RATING_Bp,
			CASE WHEN RATING = 'B' THEN 1 ELSE 0 END AS RATING_B,
			CASE WHEN RATING = 'B-' THEN 1 ELSE 0 END AS RATING_Bm,
			CASE WHEN RATING = 'CCC+' THEN 1 ELSE 0 END AS RATING_CCCp,
			CASE WHEN RATING = 'CCC' THEN 1 ELSE 0 END AS RATING_CCC,
			CASE WHEN RATING = 'CCC-' THEN 1 ELSE 0 END AS RATING_CCCm,
			CASE WHEN RATING = 'CC' THEN 1 ELSE 0 END AS RATING_CC,
			CASE WHEN RATING = 'C' THEN 1 ELSE 0 END AS RATING_C,
			CASE WHEN RATING = 'D' THEN 1 ELSE 0 END AS RATING_D,
			CASE WHEN RATING is null THEN 1 ELSE 0 END AS RATING_na, 
			CASE WHEN CREDITRISKCLASS ='Rischio 1/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS1,
			CASE WHEN CREDITRISKCLASS ='Rischio 2/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS2,
			CASE WHEN CREDITRISKCLASS ='Rischio 3/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS3,
			CASE WHEN CREDITRISKCLASS ='Rischio 4/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS4,
			CASE WHEN CREDITRISKCLASS ='Rischio 5/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS5,
			CASE WHEN CREDITRISKCLASS ='Rischio 6/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS6,
			CASE WHEN CREDITRISKCLASS ='Rischio 7/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS7,
			CASE WHEN CREDITRISKCLASS ='Rischio 8/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS8,
			CASE WHEN CREDITRISKCLASS ='Rischio 9/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS9,
			CASE WHEN CREDITRISKCLASS ='Rischio 10/10' THEN 1 ELSE 0 END AS FLG_RISKCLASS10,
			SUM(CTV_AZ_OB_EMIT) as CTV_AZ_OB_EMIT,
			SUM(CTV_AZIONARIO) AS STOCKSCounterValue,
			sum(CTV_OBBLIGAZIONARIO) AS bondsCounterValue,
			0 AS  CONCENTRATION_ISSUER ,
			SUM(CTV_AZ_OB_EMIT_INTER) CTV_AZ_OB_EMIT_INTER,
			SUM(CTV_COMPLessivo)  AS CTV_COMPLessivo,
			MAX(copertura) as copertura
		FROM  C6MARTPERIODICO.PATRIMONIO_EMITTENTI V  
				LEFT JOIN C6MARTPERIODICO.ANAG_PRODOTTI ANAG
				ON V.COD_PRODOTTO = ANAG.COD_PRODOTTO
		WHERE 
			1=1
			AND (CTV_AZIONARIO >0 OR CTV_OBBLIGAZIONARIO > 0)
		GROUP BY
			V.COD_FISCALE,
			V.RETE,
			EMITTENTE,
			RATING,
			INTERMEDIARIO,
			CREDITRISKCLASS
		) Y
GROUP BY 
	y.COD_FISCALE,
	y.RETE,
	INTERMEDIARIO,
	CREDITRISKCLASS,
	EMITTENTE,
	RATING_AAA,
RATING_AAp,
RATING_AA,
RATING_AAm,
RATING_Ap,
RATING_A,
RATING_Am,
RATING_BBBp,
RATING_BBB,
RATING_BBBm,
RATING_BBp,
RATING_BB,
RATING_BBm,
RATING_Bp,
RATING_B,
RATING_Bm,
RATING_CCCp,
RATING_CCC,
RATING_CCCm,
RATING_CC,
RATING_C,
RATING_D,
RATING_na,
	FLG_RISKCLASS1,
	FLG_RISKCLASS2,
	FLG_RISKCLASS3,
	FLG_RISKCLASS4,
	FLG_RISKCLASS5,
	FLG_RISKCLASS6,
	FLG_RISKCLASS7,
	FLG_RISKCLASS8,
	FLG_RISKCLASS9,
	FLG_RISKCLASS10
) L
 inner join #patr_compl p on p.rete = l.rete and  p.cod_fiscale = l.cod_fiscale
GROUP BY 
   l. COD_FISCALE,
     l.RETE,
     INTERMEDIARIO,
     EMITTENTE
) U
 ORDER BY U.CONCENTRATION DESC
END
-------------------------------------------------------------------------
------[C6MartPeriodico].[PL_MP_S140AnalisiRisparmioCharts]
BEGIN
--QUERY PER INTERMEDIARIO
INSERT INTO wh.PL_MP_S140AnalisiRisparmioCharts
SELECT 'PL_MP_S140AnalisiRisparmioCharts', RETE, COD_FISCALE, *FROM
(
SELECT
RETE,
COD_FISCALE,
INTERMEDIARIO,
CASE WHEN INTERMEDIARIO  IN ( 'Fideuram', 'Sanpaolo Invest') THEN 1
     ELSE 2 END AS ORDINE,
SUM(CTV)  AS CTV_TOT,
SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)  AS CTV_notCovered,
SUM(CASE WHEN RISKCLASS = 'Classe A' 
				or RISKCLASS = 'Classe B'
					or RISKCLASS = 'Classe C' 
						or RISKCLASS = 'Classe D' 
	THEN CTV ELSE 0 END)  AS CTV_CreditRisk,
SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END)  AS CTV_na,
--CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)/SUM(CTV))*100  END AS PERC_notCovered,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'Classe A' 
												or RISKCLASS = 'Classe B'
													or RISKCLASS = 'Classe C' 
														or RISKCLASS = 'Classe D' THEN CTV ELSE 0 END)
									/SUM(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END) 
)*100 END AS PERC_CreditRisk,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END) /sum(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END))*100  END as PERC_NA
FROM
(
 -- Start 1.1
SELECT 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END AS RISKCLASS,
CASE WHEN PATRBF.RETE = 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' END AS INTERMEDIARIO,
--SUM(CASE WHEN PATRBF.ID_AREA = 'Cc' AND PATRBF.CTV < 0 THEN 0 ELSE PATRBF.CTV END) AS CTV
--INIZIO INTERVENTI OMNIA
--SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area='cc' THEN 0 ELSE PATRBF.CTV END) AS ctv
SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area='cc'   THEN 0 
	     WHEN ctvself.self_ctv <0 and patrbf.id_area='self' THEN 0
	ELSE PATRBF.CTV END) AS ctv
--FINE INTERVENTI OMNIA
FROM
[C6Martperiodico].PATRIMONIO_BF PATRBF
---Per calcolare la somma algebrica dei cc 
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area='Cc'
group by cod_fiscale, rete
) ctvcc
on 
patrbf.cod_fiscale=ctvcc.cod_fiscale
and
patrbf.rete=ctvcc.rete
--fine calcolo somma cc
--INIZIO INTERVENTI OMNIA
---Per calcolare la somma algebrica dei self negativi
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as self_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area='Self'
group by cod_fiscale, rete
) ctvself
on 
patrbf.cod_fiscale=ctvself.cod_fiscale
and
patrbf.rete=ctvself.rete
--fine calcolo somma self negativi
--FINE INTERVENTI OMNIA
LEFT OUTER JOIN
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
			CASE 
				WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO + '|' + isnull(cast(PATRBF.ordinamento_progetto as varchar),'') + '|'
				--V
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('EXT','INV','PRE','RIS','LIQ')
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('CC')
					THEN 'COMPLESSIVO|BF|CC|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('NA')
					THEN 'RISFIN|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				--
			END	+ PATRBF.POSITION_ID 
--INNER JOIN C6MartPeriodico.CODIFICA_CREDITRISK CR
LEFT outer JOIN C6MartPeriodico.CODIFICA_CREDITRISK CR
ON RISCHIO_PROD.CREDITRISK = cr.profilo
--V
--
GROUP BY 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END,
CASE WHEN PATRBF.RETE = 'F' THEN 'FIDEURAM' ELSE 'SANPAOLO' END
--- End 1.1
UNION ALL
-- Start 1.2
SELECT 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
PATRTERZI.INTERMEDIARIO,
SUM(ROUND(CTV,2)) AS CTV
FROM 
[C6Martperiodico].PATRIMONIO_TERZI PATRTERZI
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6Martperiodico].pATRIMONIO_terzi
where tipo_prodotto='Conti correnti'
group by cod_fiscale, rete
) ctvcc
on
patrterzi.cod_fiscale=ctvcc.cod_fiscale
and
patrterzi.rete=ctvcc.rete
LEFT OUTER JOIN 
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG ='TIPOPRODTERZI|TERZI|' +ISNULL(PATRTERZI.DESCR_GRUPPO_PRODOTTO, PATRTERZI.TIPO_PRODOTTO)  + '|'+ PATRTERZI.COD_PRODOTTO_TERZI
left outer JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIOPROD.CREDITRISK = cr.profilo
--V
GROUP BY 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
PATRTERZI.INTERMEDIARIO,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
-- End 1.2
)H
GROUP BY
RETE,
COD_FISCALE,
INTERMEDIARIO
--------
UNION ALL
-----------
--QUERY TOTALE
SELECT
RETE,
COD_FISCALE,
'Complessivo' AS INTERMEDIARIO,
3 AS ORDINE,
SUM(CTV)  AS CTV_TOT,
SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)  AS CTV_notCovered,
SUM(CASE WHEN RISKCLASS = 'Classe A' 
				or RISKCLASS = 'Classe B'
					or RISKCLASS = 'Classe C' 
						or RISKCLASS = 'Classe D' 
	THEN CTV ELSE 0 END)  AS CTV_CreditRisk,
SUM(CASE WHEN RISKCLASS ='NA' THEN CTV ELSE 0 END)  AS CTV_na,
--CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NON COPERTO' THEN CTV ELSE 0 END)/SUM(CTV))*100  END AS PERC_notCovered,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'Classe A' 
												or RISKCLASS = 'Classe B'
													or RISKCLASS = 'Classe C' 
														or RISKCLASS = 'Classe D' THEN CTV ELSE 0 END)
									/SUM(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END) 
)*100 END AS PERC_CreditRisk,
CASE WHEN SUM(CTV)=0 THEN 0 ELSE (SUM(CASE WHEN RISKCLASS = 'NA' THEN CTV ELSE 0 END) /sum(CASE WHEN RISKCLASS <> 'NON COPERTO' THEN CTV ELSE 1 END))*100 END as PERC_NA
FROM
(
--- Start 2.1
SELECT 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
--SUM(CASE WHEN PATRBF.ID_AREA = 'Cc' AND PATRBF.CTV < 0 THEN 0 ELSE PATRBF.CTV END) AS CTV
--INIZIO INTERVENTI OMNIA
--SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area='cc'  THEN 0 ELSE PATRBF.CTV END) AS CTV
SUM(CASE WHEN ctvcc.cc_ctv <0 and patrbf.id_area='cc'  THEN 0 
		 WHEN ctvself.self_ctv <0 and patrbf.id_area='self'  THEN 0
	ELSE PATRBF.CTV END) AS CTV
--FINE INTERVENTI OMNIA
FROM
[C6Martperiodico].PATRIMONIO_BF PATRBF
--per fare la somma algebrica dei cc
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area='Cc'
group by cod_fiscale, rete
) ctvcc
on 
patrbf.cod_fiscale=ctvcc.cod_fiscale
and
patrbf.rete=ctvcc.rete
--fine somma cc
--INIZIO INTERVENTI OMNIA
--per fare la somma algebrica dei self negativi
LEFT OUTER JOIN
(select cod_fiscale, rete, sum(ctv) as self_ctv
from
[C6MARTPERIODICO].pATRIMONIO_BF 
where id_Area='Self'
group by cod_fiscale, rete
) ctvself
on 
patrbf.cod_fiscale=ctvself.cod_fiscale
and
patrbf.rete=ctvself.rete
--fine somma Self negativi
--FINE INTERVENTI OMNIA
LEFT OUTER JOIN
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
			CASE 
				WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO+ '|' + isnull(cast(PATRBF.ordinamento_progetto as varchar),'')+'|'
				--V
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('EXT','INV','PRE','RIS','LIQ')
					THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('CC')
					THEN 'COMPLESSIVO|BF|CC|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				WHEN (PATRBF.NOME_PROGETTO IS NULL) AND PATRBF.ID_AREA IN ('NA')
					THEN 'RISFIN|' + LEFT(PATRBF.ID_AREA,3) + '|'  
				--
			END	+ PATRBF.POSITION_ID 
left outer JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIO_PROD.CREDITRISK = cr.profilo
--V
--
GROUP BY 
PATRBF.RETE,
PATRBF.COD_FISCALE,
CASE	
	WHEN RISCHIO_PROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
-- End 2.1
UNION ALL
-- Start 2.2
SELECT 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END  AS RISKCLASS,
SUM(ROUND(CTV,2)) AS CTV
FROM 
[C6Martperiodico].PATRIMONIO_TERZI PATRTERZI
left outer join
(select cod_fiscale, rete, sum(ctv) as cc_ctv
from 
[C6Martperiodico].pATRIMONIO_terzi
where tipo_prodotto='Conti correnti'
group by cod_fiscale, rete
) ctvcc
on
patrterzi.cod_fiscale=ctvcc.cod_fiscale
and
patrterzi.rete=ctvcc.rete
LEFT OUTER JOIN 
[C6Martperiodico].RISCHIO_AGGREGATO RISCHIOPROD
		ON 
			PATRTERZI.RETE = RISCHIOPROD.RETE
			AND PATRTERZI.COD_FISCALE = RISCHIOPROD.COD_FISCALE
			AND RISCHIOPROD.COD_AGGREG ='TIPOPRODTERZI|TERZI|' + ISNULL(PATRTERZI.DESCR_GRUPPO_PRODOTTO, PATRTERZI.TIPO_PRODOTTO)  + '|'+ PATRTERZI.COD_PRODOTTO_TERZI
left outer  JOIN [C6Martperiodico].CODIFICA_CREDITRISK CR
ON RISCHIOPROD.CREDITRISK = cr.profilo
--
GROUP BY 
PATRTERZI.RETE,
PATRTERZI.COD_FISCALE,
CASE	
	WHEN RISCHIOPROD.COPERTURA < 100 
		THEN 'NON COPERTO'
	WHEN DESCRIZIONE IS NULL
		THEN 'NA'
	ELSE DESCRIZIONE	
END
--- End 2.2
)H
GROUP BY
RETE,
COD_FISCALE
)X
END
-------------------------------------------------------------------------
----- [C6MartPeriodico].[PL_MP_S137BISCapitaleProtetto]
   begin
   INSERT INTO wh.PL_MP_S137BISCapitaleProtetto
     SELECT 'PL_MP_S137BISCapitaleProtetto', RETE
	,CODFIS
	,DES_PROD
	,COD_CONF
	,QUOTA
	,NUMEROQUOTE
	,CONTROVALORE
	,DATARIF
	,DES_MAX
	,QUOTA_MAX
	,QUOTA_MAX_PERC
	,DATARIF_MAX
	,DES_PROT
	,QUOTA_PROT
	,NUMEROQUOTE_PROT
	,CONTROVALORE_PROT 
	,DES_PROD_TIT -- Aggiunta per E-FOI80
	FROM C6MartPeriodico.CAPPROT
	WHERE 1=1
END
-------------------------------------------------------------------------
------------ [C6MartPeriodico].[PL_S43ContoCorrenteBF] 
BEGIN
	INSERT INTO wh.PL_S43ContoCorrenteBF
	SELECT 'PL_S43ContoCorrenteBF', ANAG_CC.rete, ANAG_CC.cod_fiscale,    
		dbo.ToShortDateString(ANAG_CC.DATA_APERTURA) AS datadiSottoscrizione, 
		ANAG_CC.COD_CC AS conto, 
		cast(ANAG_CC.SALDOCONTABILE as decimal(15,2)) as Controvalore,
		cast(ANAG_CC.SALDODISPONIBILE as decimal(15,2)) as SALDO_DISPONIBILE,
        null as creditrisk ,
        'n.a.' as creditriskstring,
		0 as var,
		null as varString,
		0 as totaleVar,
		null as totaleVarString
	FROM       
		C6MartPeriodico.ANAG_CC	
	WHERE 
	 ANAG_CC.SALDOCONTABILE < 0
	ORDER BY
		ANAG_CC.SALDOCONTABILE DESC
END
-------------------------------------------------------------------------
------[C6MartPeriodico].[PL_S43BISDettaglioProdottiBF]
BEGIN 
	SELECT COUNT(*) as TOTSELFLIQ, PATRIMONIO_BF.RETE, PATRIMONIO_BF.COD_FISCALE 
	into #TOTSELFLIQ1
	FROM C6MARTPERIODICO.PATRIMONIO_BF
	WHERE ISIN in('EURO00000009', 'EURO10000007')
		AND ID_AREA = 'LIQ'
	GROUP BY PATRIMONIO_BF.RETE, PATRIMONIO_BF.COD_FISCALE 
	SELECT COUNT(*) as TOTLIQ, PATRIMONIO_BF.RETE, PATRIMONIO_BF.COD_FISCALE
	into #PATRIMONIO_BF
	FROM C6MARTPERIODICO.PATRIMONIO_BF
	WHERE ID_AREA = 'LIQ'
	GROUP BY PATRIMONIO_BF.RETE, PATRIMONIO_BF.COD_FISCALE
	INSERT INTO wh.[PL_S43BISDettaglioProdottiBF]
SELECT 'PL_S43BISDettaglioProdottiBF',	PATRBF.RETE, PATRBF.COD_FISCALE,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Pre' 
	ELSE AREA.ID_AREA 
END AS needarea,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN 'Previdenza'
	WHEN AREA.ID_AREA = 'Na'  THEN 'Non allocate'
	ELSE AREA.NOME_AREA 
END AS needareades,
CASE 
	WHEN AREA.ID_AREA = 'Pre1' OR AREA.ID_AREA = 'Pre2' THEN  3 
	ELSE AREA.ORDINAMENTO 
END AS areasortorder,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND PATRBF.NOME_PROGETTO IS NULL THEN 'Prodotti non associati a progetti'
	ELSE ISNULL(PATRBF.NOME_PROGETTO,'')
END AS nome_progetto,
ISNULL(PATRBF.ORDINAMENTO_PROGETTO,-1111) ,
--Bido
SUM(PATRBF.CTV ) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE) AS somma_controval_needarea,
SUM(PATRBF.CTV - MONIT.UTILE_PERDITA_DA_ASSOC) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE) AS versato_needarea,
CASE 
	WHEN COUNT(CASE WHEN (PATRBF.CTV - MONIT.UTILE_PERDITA_DA_ASSOC) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END as versato_needareaString,
SUM(MONIT.UTILE_PERDITA_DA_ASSOC) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE) AS MinusPlusValenza_needarea,
CASE 
	WHEN COUNT( CASE 
					WHEN MONIT.UTILE_PERDITA_DA_ASSOC IS NULL THEN 1 
					ELSE NULL 
				END ) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE) > 0 THEN 'n.d.' 
	ELSE NULL 
END AS MinusPlusValenza_needareaString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.ordinamento_progetto) 
	ELSE NULL	
END	AS somma_controval_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(PATRBF.CTV - MONIT.UTILE_PERDITA_DA_ASSOC) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.ordinamento_progetto) 
	ELSE NULL
END	AS versato_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN (PATRBF.CTV - MONIT.UTILE_PERDITA_DA_ASSOC) IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.ordinamento_progetto) > 0 
		THEN 'n.d.'
	ELSE NULL
END	AS versato_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN SUM(MONIT.UTILE_PERDITA_DA_ASSOC) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.ordinamento_progetto) 
	ELSE NULL
END	AS MinusPlusValenza_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' AND COUNT(CASE WHEN MONIT.UTILE_PERDITA_DA_ASSOC IS NULL THEN 1 ELSE NULL END) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE, PATRBF.NOME_PROGETTO, PATRBF.ordinamento_progetto) > 0	
		THEN 'n.d.'
	ELSE NULL
END	AS MinusPlusValenza_need_progString,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.VAR_PERC_PTF
	ELSE NULL
END	AS somma_var_need_prog,
CASE 
	WHEN AREA.ID_AREA = 'Inv' THEN RISCHIO_AGGR_PROG.COPERTURA
	ELSE NULL
END	AS somma_copertura_need_prog,
RISCHIO_AGGR_AREA.VAR_PERC_PTF AS var_needarea,
CASE 
	WHEN ISNULL(SUM(RISCHIO_AGGR_AREA.COPERTURA) OVER (PARTITION BY AREA.ID_AREA,	PATRBF.RETE, PATRBF.COD_FISCALE),0.00) = 0.00 
		THEN 'n.c.' 
--------------------------------------------------------------
--INIZIO INTERVENTI OMNIA QUIII				
	WHEN TOTSELFLIQ = TOTLIQ and AREA.ID_AREA = 'LIQ' 
		THEN 'n.c.' 
--FINE INTERVENTI OMNIA QUIII
--------------------------------------------------------------	
	ELSE NULL 
END AS var_needareaString,
CAST(ISNULL(RISCHIO_AGGR_AREA.COPERTURA,100) AS DECIMAL (5,2)) AS copertura_needarea,
	CASE 
	WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) 
		--V THEN '(*) Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_AREA.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
	ELSE '' 
END AS copertura_needareaString,
RISCHIO_AGGR_PROG.VAR_PERC_PTF AS var_need_prog,
CASE 
	WHEN ISNULL(RISCHIO_AGGR_PROG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
	ELSE NULL 
END AS var_need_progString,
RISCHIO_AGGR_PROG.COPERTURA AS copertura_need_prog,
--TRINGALI
	CASE 
	WHEN (ISNULL(RISCHIO_AGGR_PROG.copertura,100) < 100) 
		--v THEN '(*) Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_PROG.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
		THEN 'Grado di copertura: ' + REPLACE(CAST(CAST(RISCHIO_AGGR_PROG.COPERTURA AS DECIMAL (5,2)) AS VARCHAR),'.',',') + '%'  
	ELSE '' 
END AS copertura_need_progString,
	case when (dbo.TOSHORTDATESTRING(MONIT.DATA_ASSOCIAZIONE) is null 
			 and patrbf.id_area='liq'
			 and (patrbf.tipo_prodotto='CC' 
			 or   patrbf.isin in('EURO00000009', 'EURO10000007')))
	then	dbo.TOSHORTDATESTRING(C6MartPeriodico.getTrimestre2(getdate(),0))
--FINE INTERVENTI OMNIA
	else
--disasteriscare
		--dbo.TOSHORTDATESTRING(MONIT.DATA_ASSOCIAZIONE) 
--cancellare inizio
	case when (dbo.TOSHORTDATESTRING(MONIT.DATA_ASSOCIAZIONE) is null 
			and patrbf.chiave_progetto = '2205396'
			and patrbf.tipo_prodotto = 'FI')
		then	'26/06/2014'
			else
				dbo.TOSHORTDATESTRING(MONIT.DATA_ASSOCIAZIONE) 
		end
--cancellare fine
	end AS dataAssociazione, -- CAMBIATA TRINGALI--marianna, cambiata per i cc senza data di associazione
PATRBF.ID_CONTRATTO AS ContrattoDossier, 
--V
CASE WHEN PATRBF.TIPO_PRODOTTO <> 'CC' THEN ANAGPROD.DESCR_PRODOTTO
	 ELSE ANAGPROD.DESCR_PRODOTTO+' '+SUBSTRING(COD_CC,4,2) + '/' + SUBSTRING(COD_CC,6,LEN(ANAG_CC.COD_CC))
END AS Descrizione,
--ANAGPROD.DESCR_PRODOTTO AS Descrizione,
PATRBF.CTV AS Controvalore, 
CASE WHEN PATRBF.REND_NON_RAPPR=1 THEN NULL ELSE isnull(MONIT.VERSATO_NETTO_DA_ASSOC,0) end  AS VersatoNetto, 
CASE WHEN (MONIT.VERSATO_NETTO_DA_ASSOC IS NULL OR PATRBF.REND_NON_RAPPR=1) THEN 'n.d.' ELSE NULL END as VersatoNettoString,
CASE WHEN PATRBF.REND_NON_RAPPR=1 THEN NULL ELSE  isnull(MONIT.UTILE_PERDITA_DA_ASSOC,0) END AS MinusPlusValenza, 
CASE WHEN (MONIT.UTILE_PERDITA_DA_ASSOC IS NULL OR PATRBF.REND_NON_RAPPR=1)  THEN 'n.d.' ELSE NULL END as MinusPlusValenzaString,
case when (patrbf.tipo_prodotto ='CC') then 0.00 
else RISCHIO_PROD.VAR_PERC_PTF
end AS VaRprodotto, 
--INIZIO INTERVENTI OMNIA
--CASE WHEN ISNULL(RISCHIO_PROD.Copertura,0.00) = 0.00  and patrbf.tipo_prodotto <> 'CC' THEN 'n.c.' ELSE NULL END as varProdottoString,
CASE WHEN ISNULL(RISCHIO_PROD.Copertura,0.00) = 0.00 and patrbf.tipo_prodotto <>'CC' THEN 'n.c.' 
     WHEN patrbf.isin in ('EURO00000009', 'EURO10000007' )THEN 'n.c.'
ELSE NULL END as varProdottoString,
--FINE INTERVENTI OMNIA
--INIZIO INTERVENTI OMNIA
--case when (patrbf.tipo_prodotto ='CC') then 100.00
case when (patrbf.tipo_prodotto ='CC') or (patrbf.isin in('EURO00000009', 'EURO10000007')) then 100.00
--FINE INTERVENTI OMNIA
else RISCHIO_PROD.Copertura 
end AS Coperturaprodotto,
PATRBF.REND_ANNO AS PerformanceYTD, 
PATRBF.REND_SOTTOSCRIZIONE AS performanceDS,
PARTVIA_DISINV AS partitaViaggiante,
CASE WHEN (ISNULL(RISCHIO_AGGR_AREA.copertura,100) < 100) THEN '*' ELSE '' END AS nota_needarea,
    RISCHIO_PROD.CREDITRISK as creditrisk,
    CASE 
--INIZIO INTERVENTI OMNIA
--		WHEN ISNULL(RISCHIO_PROD.COPERTURA,0.00) = 0.00 and patrbf.tipo_prodotto <> 'CC' THEN 'n.c.' 
    	WHEN (ISNULL(RISCHIO_prod.COPERTURA,0.00) = 0.00 
	             and patrbf.tipo_prodotto <> 'CC') 
	             or  (patrbf.isin in('EURO00000009', 'EURO10000007')) 
	    THEN 'n.c.' 
--FINE INTERVENTI OMNIA	
		WHEN RISCHIO_PROD.CREDITRISK is null THEN 'n.a.'
		ELSE NULL 
	END as creditriskstring,
--	CASE 
--	WHEN RISCHIO_PROD.CREDITRISKEMIT IS NULL THEN 'n.a.'
--		ELSE cast(RISCHIO_PROD.CREDITRISKEMIT as varchar(20))
--	END as creditriskemit
	RISCHIO_PROD.CREDITRISKEMIT as creditriskemit
FROM 
C6MartPeriodico.PATRIMONIO_BF PATRBF
INNER JOIN 
C6MartPeriodico.ANAG_PRODOTTI ANAGPROD 
ON 
	ANAGPROD.COD_PRODOTTO = PATRBF.COD_PRODOTTO
INNER JOIN 
C6MartPeriodico.AREA_BISOGNO AREA 
ON 
	-- LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA 
	(LEFT(PATRBF.ID_AREA,3) = AREA.ID_AREA and AREA.ID_AREA <>'self') or (PATRBF.ID_AREA='self' and  AREA.ID_AREA ='self')
LEFT JOIN 
C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_PROD 
ON 
	PATRBF.RETE= RISCHIO_PROD.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_PROD.COD_FISCALE
	AND RISCHIO_PROD.COD_AGGREG = 
				CASE 
					WHEN (PATRBF.NOME_PROGETTO IS NOT NULL)
						THEN 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO + '|'
						 + cast (PatrBF.ordinamento_progetto as varchar) + '|'
					when LEFT(PATRBF.ID_AREA,3)='Na' then 'RISFIN|NA|'
					ELSE 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' 
				END
--		END + PATRBF.POSITION_ID 
		+ PATRBF.POSITION_ID 
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_PROG
	ON PATRBF.RETE= RISCHIO_AGGR_PROG.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_PROG.COD_FISCALE
	AND RISCHIO_AGGR_PROG.COD_AGGREG = 'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) + '|' + PATRBF.NOME_PROGETTO + '|'
						 + cast (PatrBF.ordinamento_progetto as varchar) 
LEFT JOIN #PATRIMONIO_BF bf on bf.rete = PATRBF.rete and bf.cod_fiscale = PATRBF.cod_fiscale
LEFT JOIN #TOTSELFLIQ1 tot on  tot.rete = PATRBF.rete and tot.cod_fiscale = PATRBF.cod_fiscale
LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO RISCHIO_AGGR_AREA
	ON PATRBF.RETE= RISCHIO_AGGR_AREA.RETE
	AND PATRBF.COD_FISCALE= RISCHIO_AGGR_AREA.COD_FISCALE
	AND RISCHIO_AGGR_AREA.COD_AGGREG =   case 
		when LEFT(PATRBF.ID_AREA,3) = 'Na' then 'RISFIN|NA'
         else  'RISFIN|PIRAMIDE|' + LEFT(PATRBF.ID_AREA,3) 
		end
--	AND RISCHIO_AGGR_AREA.COD_AGGREG = 
--		CASE AREA.ID_AREA 
--			WHEN 'Na' THEN 'RISORSENONASSOCIATE' 
--			ELSE 'COMPLESSIVO|BF|' + LEFT(PATRBF.ID_AREA,3) 
--		END
LEFT JOIN
--MODIFICA TRINGALI PER PRENDERE DETTAGLIO MONITORAGGIO
C6MartPeriodico.MONITORAGGIO_DETTAGLIO MONIT
ON
	PATRBF.RETE = MONIT.RETE
	AND PATRBF.COD_FISCALE = MONIT.COD_FISCALE
	--AND LEFT(PATRBF.ID_AREA, 3) = MONIT.ID_AREA
    and PATRBF.POSITION_ID=MONIT.POSITION_ID
	--AND CASE WHEN PATRBF.NOME_PROGETTO IS NULL THEN 'XXX' ELSE PATRBF.NOME_PROGETTO END = MONIT.NOME_PROGETTO
--Bido to get Code_CC field
LEFT OUTER JOIN C6MartPeriodico.ANAG_CC
ON 
	ANAG_CC.COD_FISCALE = PATRBF.COD_FISCALE
	AND ANAG_CC.RETE = PATRBF.RETE
	AND cast(ANAG_CC.cod_cc as integer ) = substring(PATRBF.position_id,72,9)
LEFT OUTER JOIN C6MARTPERIODICO.MONITORAGGIO_ATTUALE MONATT
ON 
	PATRBF.RETE = MONATT.RETE
	AND PATRBF.COD_FISCALE = MONATT.COD_FISCALE
	AND 
		(PATRBF.ID_AREA=(CASE WHEN MONATT.ID_AREA='Exr' THEN 'Ext' ELSE MONATT.ID_AREA END) AND PATRBF.ID_AREA <> 'INV'
		OR
		PATRBF.ID_AREA = 'INV' AND PATRBF.ID_AREA = MONATT.ID_AREA AND PATRBF.ORDINAMENTO_PROGETTO = MONATT.ORDINAMENTO_PROGETTO
		)
--blocchiamo il monitoraggio per i progetti a ctv=0
	--And ctv_monitorato>0
WHERE 1 = 1
 AND ( PATRBF.CTV <> 0 
 --E-DEFAULT4 per gestire l'esposizione dei prodotti con ctv = 0 delle banche in default - 18/1/2016
 or (PATRBF.tipo_prodotto = 'DT' and 
 PATRBF.cod_interno in ('08558830','08594680','04880930','04867780','03972990',
 '04281500','04539780','04657780','04966850','04119400','04931400',
 '04556320',
 '04119600','04291890','04064530'
)))
 --fine E-DEFAULT4
ORDER BY 
	AREASORTORDER, PATRBF.NOME_PROGETTO, PATRBF.CTV DESC  -- modifica TRINGALI
drop table #PATRIMONIO_BF
END
-------------------------------------------------------------------------
------ [C6MartPeriodico].[PL_S88PatrimonioNonConsideratoNelCalcoloDelRendimento]
BEGIN
	INSERT INTO wh.PL_S88PatrimonioNonConsideratoNelCalcoloDelRendimento
	SELECT 'PL_S88PatrimonioNonConsideratoNelCalcoloDelRendimento', PATR_BF.RETE,
		PATR_BF.COD_FISCALE,
		PATR_BF.ID_AREA AS Need_Area,
		PATR_BF.ID_CONTRATTO AS Contratto,
		CASE
			WHEN PATR_BF.ID_AREA IN ('Ris', 'Ext', 'Liq') THEN AREA.NOME_AREA
			ELSE ltrim(rtrim(PATR_BF.NOME_PROGETTO))
		END AS Area_O_Nome_Progetto,
		--PRODOTTI.DESCR_PRODOTTO AS Descrizione,
		CASE WHEN PATR_BF.TIPO_PRODOTTO <> 'CC' THEN PRODOTTI.DESCR_PRODOTTO
			 ELSE PRODOTTI.DESCR_PRODOTTO+' '+SUBSTRING(COD_CC,4,2) + '/' + SUBSTRING(COD_CC,6,LEN(ANAG_CC.COD_CC))
		END AS Descrizione,
		PATR_BF.PARTVIA_DISINV AS PartitaViaggiante,
		SUM(PATR_BF.CTV) OVER (PARTITION BY  PATR_BF.RETE,
		PATR_BF.COD_FISCALE,PATR_BF.POSITION_ID) AS Controvalore,
		dbo.ToShortDateString(PATR_BF.DATA_SOTTOSCRIZIONE) AS DataSottoscrizione
	FROM
		C6MartPeriodico.PATRIMONIO_BF AS PATR_BF
		INNER JOIN C6MartPeriodico.AREA_BISOGNO AS AREA ON
			PATR_BF.ID_AREA = AREA.ID_AREA
		INNER JOIN C6MartPeriodico.ANAG_PRODOTTI AS PRODOTTI ON
			PATR_BF.COD_PRODOTTO = PRODOTTI.COD_PRODOTTO
		--V La sezione deve uscire soltanto per aree monitorate
		INNER JOIN C6MartPeriodico.MONITORAGGIO_ATTUALE M ON
			PATR_BF.RETE = M.RETE AND PATR_BF.COD_FISCALE = M.COD_FISCALE
			AND(
				(PATR_BF.ID_AREA = M.ID_AREA  AND PATR_BF.ID_AREA <> 'INV')
				OR
				(PATR_BF.ID_AREA = 'INV' AND PATR_BF.ID_AREA = M.ID_AREA AND PATR_BF.ORDINAMENTO_PROGETTO = M.ORDINAMENTO_PROGETTO)
			)
		LEFT OUTER JOIN C6MartPeriodico.ANAG_CC	ON 
			ANAG_CC.COD_FISCALE = PATR_BF.COD_FISCALE
			AND ANAG_CC.RETE = PATR_BF.RETE
			AND cast(ANAG_CC.cod_cc as integer ) = substring(PATR_BF.position_id,72,9)
	WHERE
		PATR_BF.REND_NON_RAPPR = 1
	ORDER BY
		Area_O_Nome_Progetto
END
-------------------------------------------------------------------------
----- [C6MartPeriodico].[PL_S82BisDatiSintetici]
BEGIN
	INSERT INTO wh.PL_S82BisDatiSintetici
	SELECT DISTINCT 'PL_S82BisDatiSintetici',
	 BF.RETE,
		BF.COD_FISCALE,
		BF.ORDINAMENTO_PROGETTO,
		'Inv' AS need_area,
		ltrim(rtrim(ISNULL(PIRMOD.NOME_PROGETTO,BF.NOME_PROGETTO))) AS NOME_PROGETTO,
		ISNULL(RA.VAR_PERC_PTF,0) AS var_needarea,
		CASE 
			WHEN RA.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RA.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS var_needareaString,
		ISNULL(RA.COPERTURA,0) AS copertura_needarea,
		CASE 
			WHEN RA.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RA.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS copertura_needareaString,
		PIRMOD.ORIZZ_TEMP AS orizzonte_Pianificato,
		C6MartPeriodico.getDescFromDate(DATEDIFF(m,C6MartPeriodico.getTrimestre(GETDATE(),0),(DATEADD(yy,PIRMOD.ORIZZ_TEMP_NUM,PIRMOD.DATA_PIANIF)) )) AS durataResidua,
		SUM(BF.CTV) OVER (PARTITION BY BF.RETE, BF.COD_FISCALE, BF.NOME_PROGETTO, bf.ordinamento_progetto) AS ControvaloreAttuale
	FROM
		C6MartPeriodico.PATRIMONIO_BF AS BF
		LEFT OUTER JOIN C6MartPeriodico.RISCHIO_AGGREGATO AS RA
			ON BF.RETE = RA.RETE
			AND BF.COD_FISCALE = RA.COD_FISCALE
			--V AND RA.COD_AGGREG = 'PIRAMIDE|Inv'
			AND RA.COD_AGGREG = 'RISFIN|PIRAMIDE|Inv|'+ BF.NOME_PROGETTO + '|' + cast(bf.ordinamento_progetto as varchar)
			--
		INNER JOIN C6MartPeriodico.PIRAMIDE_MOD AS PIRMOD
			ON BF.RETE = PIRMOD.RETE
			AND BF.COD_FISCALE = PIRMOD.COD_FISCALE
			--AND BF.NOME_PROGETTO = PIRMOD.NOME_PROGETTO
			AND BF.ORDINAMENTO_PROGETTO = PIRMOD.ORDINAMENTO_PROGETTO
			AND PIRMOD.ID_AREA = 'Inv'
		INNER JOIN C6MartPeriodico.vPatrimonioBFAggregato AS BFAggr
			ON BF.RETE = BFAggr.RETE
			AND BF.COD_FISCALE = BFAggr.COD_FISCALE
		LEFT OUTER JOIN C6MARTPERIODICO.MONITORAGGIO_ATTUALE AS MONIT
			ON BF.RETE = MONIT.RETE
			AND BF.COD_FISCALE = MONIT.COD_FISCALE
			AND BF.ID_AREA = MONIT.ID_AREA
			AND BF.NOME_PROGETTO = MONIT.NOME_PROGETTO
			AND BF.ORDINAMENTO_PROGETTO = MONIT.ORDINAMENTO_PROGETTO
	WHERE 1=1
		AND BF.ID_AREA = 'Inv'
		END
		--AND BF.ORDINAMENTO_PROGETTO=1521667
-------------------------------------------------------------------------
----- [C6MartPeriodico].[PL_S76AlternativaPatrimonioNonRappresentabileAssettClass] 
begin
INSERT INTO wh.PL_S76AlternativaPatrimonioNonRappresentabileAssettClass
SELECT 'PL_S76AlternativaPatrimonioNonRappresentabileAssettClass', * FROM
(
	SELECT  
		PATRBF.RETE,
		PATRBF.COD_FISCALE,
		PATRBF.ID_CONTRATTO as Contratto,
		CASE WHEN AREA.NOME_AREA LIKE 'Previdenza%' THEN 'Previdenza' ELSE AREA.NOME_AREA END as Area,
		CASE
		WHEN area.ID_AREA IN ('Pre1', 'Pre2') THEN 'Pre'
		 ELSE area.ID_AREA end as NEEDAREA,
		PATRBF.NOME_PROGETTO as Progetto,
		patrbf.chiave_progetto as ord_progetto,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) as DataSottoscrizione,
		ANAGP.DESCR_PRODOTTO AS Descrizione,
		PATRBF.CTV as Controvalore,
		PATRBF.CTV as controvalore_contratto,
		PATRBF.PARTVIA_DISINV as PartitaViaggiante,
		case when PATRBF.RETE = 'F' then 'Fideuram'	else 'Sanpaolo Invest' end as Intermediario
		--patrbf.ordinamento_progetto
	FROM 
		C6MartPeriodico.PATRIMONIO_BF PATRBF
	INNER JOIN
		C6MartPeriodico.AREA_BISOGNO AREA
		ON
			PATRBF.ID_AREA = AREA.ID_AREA
	INNER JOIN 
		C6MartPeriodico.ANAG_PRODOTTI ANAGP
		ON 
			PATRBF.COD_PRODOTTO = ANAGP.COD_PRODOTTO
	LEFT OUTER JOIN 
		C6MartPeriodico.ASSET_PERC ASSETPERC 
		ON 
			PATRBF.COD_PRODOTTO = ASSETPERC.COD_PRODOTTO
			AND ASSETPERC.LIVELLO = 1
	WHERE 1 = 1
		AND PATRBF.TIPO_PRODOTTO <> 'ASUL'
		AND ASSETPERC.COD_PRODOTTO IS NULL
        AND PATRBF.CTV <> 0.00
UNION ALL
SELECT  PATRBF.RETE,
		PATRBF.COD_FISCALE,
		PATRBF.ID_CONTRATTO as Contratto,
		CASE WHEN AREA.NOME_AREA LIKE 'Previdenza%' THEN 'Previdenza' ELSE AREA.NOME_AREA END as Area,
		CASE
		WHEN area.ID_AREA IN ('Pre1', 'Pre2') THEN 'Pre'
		 ELSE area.ID_AREA end as NEEDAREA,
		PATRBF.NOME_PROGETTO as Progetto,
		patrbf.chiave_progetto as ord_progetto,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE) as DataSottoscrizione,
		ANAGP.DESCR_PRODOTTO AS Descrizione,
		sum(ASUL.CTV) as Controvalore,
		sum(ASUL.CTV) as controvalore_contratto,
		Max(PATRBF.PARTVIA_DISINV) as PartitaViaggiante,
		case when PATRBF.RETE = 'F' then 'Fideuram'	else 'Sanpaolo Invest' end as Intermediario
		--patrbf.ordinamento_progetto
	FROM
		C6MartPeriodico.PATRIMONIO_BF PATRBF
	INNER JOIN
		C6MartPeriodico.AREA_BISOGNO AREA
		ON
			PATRBF.ID_AREA = AREA.ID_AREA
	INNER JOIN 
		C6MartPeriodico.ANAG_PRODOTTI ANAGP
		ON 
			PATRBF.COD_PRODOTTO = ANAGP.COD_PRODOTTO
	INNER JOIN 
		C6MartPeriodico.DETTAGLIO_ASUL ASUL
		ON 
			PATRBF.RETE = ASUL.RETE
			AND PATRBF.COD_FISCALE = ASUL.COD_FISCALE
			AND PATRBF.ID_CONTRATTO = ASUL.ID_CONTRATTO
	left JOIN 
			C6MartPeriodico.ASSET_PERC ASSETPERC
			ON 
             (
				ASSETPERC.COD_PRODOTTO = ASUL.COD_PRODOTTO
				---no SKANDIA
				AND ASUL.COD_ISIN_SOTT = ''
				AND ASSETPERC.LIVELLO = 1
              )
           or
			 (  --SKANDIA
			ASSETPERC.COD_ISIN = ASUL.COD_ISIN_SOTT
			AND ASSETPERC.COD_MAF = ASUL.COD_MAF_SOTT
			AND ASSETPERC.COD_INTERNO = ASUL.COD_INTERNO
            AND rtrim(ASSETPERC.COD_SOTTOPRODOTTO) = ASUL.COD_SOTTOPRODOTTO
			AND ASSETPERC.LIVELLO = 1
			 )
		WHERE
		ASSETPERC.COD_PRODOTTO IS NULL
		AND PATRBF.TIPO_PRODOTTO = 'ASUL'
  GROUP BY 
      PATRBF.RETE,
		PATRBF.COD_FISCALE, PATRBF.ID_CONTRATTO,
     CASE WHEN AREA.NOME_AREA LIKE 'Previdenza%' THEN 'Previdenza' ELSE AREA.NOME_AREA END,
		CASE
		WHEN area.ID_AREA IN ('Pre1', 'Pre2') THEN 'Pre'
		 ELSE area.ID_AREA end,
        PATRBF.NOME_PROGETTO,
		patrbf.chiave_progetto,
		dbo.TOSHORTDATESTRING(PATRBF.DATA_SOTTOSCRIZIONE),
		ANAGP.DESCR_PRODOTTO 
		)XX
END
-------------------------------------------------------------------------
------------------------------- [C6MartPeriodico].[PL_D_S170RischioDiversificazione]
BEGIN
	select count(*) as contaCC, cod_fiscale, rete
	into #contaCCC
	from c6martperiodico.patrimonio_Bf
	where tipo_prodotto = 'CC' 
	group by cod_fiscale, rete
	select count(*) as contaPOS, cod_fiscale, rete
	into #contaPOSS
	from c6martperiodico.patrimonio_Bf
	group by cod_fiscale, rete
    SELECT isnull(sum(ctv),0) as ctvbf, cod_fiscale, rete
	INTO #ctvbf
	FROM  c6martperiodico.patrimonio_bf  			
	where CTV > 0
	group by cod_fiscale, rete
	SELECT isnull(sum(ctv),0) as ctvterzi, cod_fiscale, rete 
	INTO #ctvterzi
	FROM  c6martperiodico.patrimonio_terzi  			
	where CTV > 0
	group by cod_fiscale, rete 
	INSERT INTO wh.PL_D_S170RischioDiversificazione
SELECT 'PL_D_S170RischioDiversificazione',K.RETE,K.COD_FISCALE,
K.COD_FISCALE,
K.RETE,
CASE 
	when cod_Aggreg = 'COMPLESSIVO|BF' then COALESCE(ctvbf,0)
	when cod_Aggreg = 'COMPLESSIVO|TERZI' then COALESCE(ctvterzi,0)
	when cod_Aggreg = 'COMPLESSIVO' then COALESCE(ctvbf,0) + COALESCE(ctvterzi,0)
	else 0
END AS CTV_AGGREG,	
K.CREDITRISK,
CASE 
	WHEN (COALESCE(contaPOS,0) - COALESCE(contacc,0) = 0) THEN 0
	ELSE VAR_PERC_PTF 
END AS VAR,
CASE WHEN ISNULL(COPERTURA,0.00) = 0.00 AND COALESCE(contaPOS,0) - COALESCE(contacc,0) <> 0 THEN 'n.c.' ELSE NULL END as varString,
CASE 
	WHEN (ISNULL(copertura,100) < 100) AND COALESCE(contaPOS,0) - COALESCE(contacc,0) <> 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
full outer join #contaCCC cc on k.COD_FISCALE = cc.cod_fiscale and k.Rete = cc.rete
full outer join #contaPOSS pos on k.COD_FISCALE = pos.cod_fiscale and k.Rete = pos.rete
full outer join #ctvbf bf on k.COD_FISCALE = bf.cod_fiscale and k.Rete = bf.rete
full outer join #ctvterzi terzi on k.COD_FISCALE = terzi.cod_fiscale and k.Rete = terzi.rete
WHERE
COD_AGGREG IN ('COMPLESSIVO|BF', 'COMPLESSIVO', 'COMPLESSIVO|TERZI')
ORDER BY ordine
END 
-------------------------------------------------------------------------
----------------------------------[C6MartPeriodico].[PL_S96RischiomercatoRischiocredito]
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
 truncate table wh.PL_S96RischiomercatoRischiocredito
 INSERT INTO wh.PL_S96RischiomercatoRischiocredito
    SELECT 'PL_S96RischiomercatoRischiocredito',  RETE, COD_FISCALE, * 
	FROM (
	SELECT
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    PATRBF.INSTITUTENAME,
    CTV,
    M.PROFILO_ASS AS CODICEPROFILO,
    CR.MAX_VAR AS  VARMAX,
    RISK_AGG.VAR_PERC_PTF AS VAR ,
    	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END  AS VARSTRING,
    RISK_AGG.CREDITRISK  RISKCLASS,
        	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
        WHEN RISK_AGG.creditrisk is null THEN 'n.a.' 
        WHEN RISK_AGG.creditrisk = 0.00 THEN 'n.a.' 
		ELSE NULL 
	END AS  RISKCLASSSTRING,
    ISNULL(RISK_AGG.COPERTURA,0.00) AS COVERAGE,
--V La copertura viene valorizzata con un valore da 0 da 100
  --  	CASE 
	--	WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
--		ELSE 
NULL 
--	END 
AS COVERAGESTRING,
    M.RISKCLASS AS RISKCLASSMAX,
    round((SUM(CTV) OVER (PARTITION BY PATRBF.COD_FISCALE,PATRBF.RETE, PATRBF.INSTITUTENAME) / 
    -- 16.07.2011 COLAIANNI CONSOLI GESTIONE DIVISIONE PER ZERO
    CASE WHEN ( SUM(CTV) OVER (PARTITION BY PATRBF.RETE, PATRBF.COD_FISCALE) ) = 0
		 THEN 1
	     ELSE ( SUM(CTV) OVER (PARTITION BY PATRBF.RETE, PATRBF.COD_FISCALE) )
    END)		
    *100 ,2)AS PERCENTAGE,
	--V
	ORDINE,
	RISK_AGG.Ully_perc
    FROM
    (
    select 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    CASE WHEN PATRBF.RETE='F' THEN 'Patrimonio Fideuram' ELSE 'Patrimonio Sanpaolo Invest' END AS INSTITUTENAME,
    SUM(PATRBF.CTV) AS CTV,
	--V
	1 as ORDINE,
	RISK_AGG.Ully_perc
    from
    c6martperiodico.patrimonio_bf  PATRBF,C6MartPeriodico.RISCHIO_AGGREGATO RISK_AGG
    where 
    1=1
    and PATRBF.COD_FISCALE = RISK_AGG.COD_FISCALE 
    and PATRBF.rete= RISK_AGG.rete    
    and PATRBF.CTV > 0
    and
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' --or
      --RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )
   GROUP BY 
   PATRBF.RETE,
   PATRBF.COD_FISCALE,
	RISK_AGG.Ully_perc
  --  CASE WHEN PATRBF.RETE='F' THEN 'Patrimonio Fideuram' ELSE 'Patrimonio Sanpaolo Invest' END
    UNION
    SELECT 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    'Patrimonio altri Istituti' AS INSTITUTENAME,
    SUM(ROUND(TERZI.CTV,2)) AS CTV,
	--V
	2 as ORDINE,
	RISK_AGG.Ully_perc
    FROM
    c6martperiodico.PATRIMONIO_TERZI  TERZI,C6MartPeriodico.RISCHIO_AGGREGATO RISK_AGG
    where 
    1=1
    and TERZI.COD_FISCALE = RISK_AGG.COD_FISCALE 
    and TERZI.rete= RISK_AGG.rete 
    and TERZI.CTV > 0
    and
    (
      --RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' or
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )    
    GROUP BY 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    RISK_AGG.Ully_perc
    ) PATRBF
    LEFT OUTER JOIN 
    c6martperiodico.MIFID AS M
    ON 
    PATRBF.COD_FISCALE=M.COD_FISCALE
    AND PATRBF.RETE=M.RETE
	LEFT OUTER JOIN c6martperiodico.CODIFICA_RISCHIO AS CR
	ON M.PROFILO_ASS = CR.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.CODIFICA_CREDITRISK  CK
    ON 
    M.riskclass=CK.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.RISCHIO_AGGREGATO  RISK_AGG
    ON 
    PATRBF.COD_FISCALE=RISK_AGG.COD_FISCALE
    AND PATRBF.RETE=RISK_AGG.RETE
    AND 
    (case when  RISK_AGG.COD_AGGREG = 'COMPLESSIVO|BF' and PATRBF.RETE= 'F'  then 'Patrimonio Fideuram' 
          WHEN  RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' and PATRBF.RETE= 'S'  then 'Patrimonio Sanpaolo Invest'
          else 'Patrimonio altri Istituti' end)= PATRBF.INSTITUTENAME
   where
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|BF' or
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO|TERZI'
    )
    UNION ALL
    SELECT 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    'Patrimonio Complessivo' AS INSTITUTENAME,
    SUM(CTV),
    MAX(M.PROFILO_ASS) AS CODICEPROFILO,
    MAX(CR.MAX_VAR) AS  VARMAX,
    MAX(RISK_AGG.VAR_PERC_PTF) AS VAR ,
    MAX(	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END) AS VARSTRING,
    MAX(RISK_AGG.CREDITRISK)  RISKCLASS,
    MAX(
         	case	WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
        WHEN RISK_AGG.creditrisk is null THEN 'n.a.' 
        WHEN RISK_AGG.creditrisk = 0.00 THEN 'n.a.' 
		ELSE NULL 
	END )
      AS  RISKCLASSSTRING,
    MAX(ISNULL(RISK_AGG.COPERTURA,0.00)) AS COVERAGE,
    MAX(   	CASE 
		WHEN ISNULL(RISK_AGG.COPERTURA,0.00) = 0.00 THEN 'n.c.' 
		ELSE NULL 
	END) AS COVERAGESTRING,
    --MAX(CK.DESCRIZIONE) AS RISKCLASSMAX,
	MAX(M.RISKCLASS) AS RISKCLASSMAX,
    100 AS PERCENTAGE,
	--V
	3 AS ORDINE,
	RISK_AGG.Ully_perc
    FROM
    (
    select 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    SUM(PATRBF.CTV) AS CTV
    from
    c6martperiodico.patrimonio_bf  PATRBF
    where 
    1=1 
    and PATRBF.CTV > 0    
    GROUP BY 
    PATRBF.RETE,
    PATRBF.COD_FISCALE
    UNION
    SELECT 
    TERZI.RETE,
    TERZI.COD_FISCALE,
    SUM(ROUND(TERZI.CTV,2)) AS CTV
    FROM
    c6martperiodico.PATRIMONIO_TERZI  TERZI
        where 
    1=1 
    and TERZI.CTV > 0       
     GROUP BY 
    TERZI.RETE,
    TERZI.COD_FISCALE
    ) PATRBF
    LEFT OUTER JOIN 
    c6martperiodico.MIFID AS M
    ON 
    PATRBF.COD_FISCALE=M.COD_FISCALE
    AND PATRBF.RETE=M.RETE
	LEFT OUTER JOIN c6martperiodico.CODIFICA_RISCHIO AS CR
	ON M.PROFILO_ASS = CR.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.CODIFICA_CREDITRISK  CK
    ON 
      M.riskclass=CK.PROFILO
    LEFT OUTER JOIN 
    c6martperiodico.RISCHIO_AGGREGATO  RISK_AGG
    ON 
    PATRBF.COD_FISCALE=RISK_AGG.COD_FISCALE
    AND PATRBF.RETE=RISK_AGG.RETE
        where  
    (
      RISK_AGG.COD_AGGREG= 'COMPLESSIVO'
    )
    GROUP BY 
    PATRBF.RETE,
    PATRBF.COD_FISCALE,
    RISK_AGG.Ully_perc
	--V
	)X
	order by ordine
	END
-------------------------------------------------------------------------
-------------------- [C6MartPeriodico].[PL_S80Alternativa]
BEGIN
   SELECT COUNT(*) as MONIT_ATTIV, RETE, COD_FISCALE
       into #aa2
    FROM C6MARTPERIODICO.MONITORAGGIO_ATTUALE
       GROUP BY RETE, COD_FISCALE
       SELECT COUNT(*) as MONIT_INIT, RETE, COD_FISCALE
       into #ab2
       FROM C6MARTPERIODICO.MONITORAGGIO_INIZIALE
       GROUP BY  RETE, COD_FISCALE
       select  a.RETE, a.COD_FISCALE
       into #pos2
       from #aa2 a inner join #ab2 b on a.rete = b.rete and a.COD_FISCALE = b.COD_FISCALE
       INSERT INTO wh.PL_S80Alternativa
       SELECT 'PL_S80Alternativa' as ProcedureName, v.RETE as i_rete, v.Cod_Fiscale as i_codiceFiscale, v.[RETE]
      ,v.[Cod_Fiscale] 
      ,[Fase]
      ,[DataFase]
      ,[Partita_viaggiante]
      ,[CTV_EXT]
      ,[CTV_INV]
      ,[CTV_PRE]
      ,[CTV_RIS]
      ,[CTV_LIQ]
      ,[RisorseAllocate]
      ,[RisorseNonAllocate]
      ,[RisorseFinanziarie]
      ,[Contocorrente]
      ,[ctvself]
      ,[TotalePatrimonio]
      ,[DettMovS80] DettMov
      ,[NumeroAsterischiNota]
  FROM [C6MartPeriodico].[TB_S80_S129_EvoluzioneCTVPatrimonio] v
  inner join #pos2 p on p.rete = v.rete and p.Cod_Fiscale = v.Cod_Fiscale
END
----------------------------------------------
--maledetti
begin
truncate table 	wh.Maledetti
insert into wh.Maledetti --70 minutes
(
[i_CodiceFiscale]
      ,[i_Rete]
      ,[Rete]
      ,[NomeRete]
      ,[Agente]
      ,[CognomeAgente]
      ,[NomeAgente]
      ,[IndirizzoAgente]
      ,[CapAgente]
      ,[CittaAgente]
      ,[TelefonoAgente]
      ,[CodiceFiscale]
      ,[CognomeCliente]
      ,[NomeCliente]
      ,[ProfiloIsAct]
      ,[PatrimonioNonRappresentabile]
      ,[PartiteViaggiantiDisinv]
      ,[PartiteViaggiantiInv]
      ,[ContoCorrente]
      ,[PatrimonioBancaFideuramCtvAlNettoContoCorrente]
      ,[RisorseNonAssociate]
      ,[Patrimonioaltroctv]
      ,[Patrimonioimmobiliarectv]
      ,[PatrimonioTerzictv]
      ,[PatrimonioTerziCtvAlNettoContoCorrente]
      ,[PatrimonioTerziContoCorrente]
      ,[Patrimoniobancafideuramctv]
      ,[Patrimoniocomplessivototalectv]
      ,[NumeroIntermediari]
      ,[CodiceContratto]
      ,[tip_contratto]
      ,[contrattoold]
      ,[NoMonitoraggio]
      ,[descrizioneDiagnosi]
      ,[idModelloDiagnosi]
      ,[idReportDiagnosi]
      ,[descrizioneMonitoraggio]
      ,[idReportMonitoraggio]
      ,[idModelloMonitoraggio]
      ,[AdesioneSuccessivaAvanzato]
      ,[VaRRisorseNonAssociate]
      ,[CoperturaRisorseNonAssociate]
      ,[VaRTotaleRisorseFinanziarie]
      ,[CoperturaTotaleRisorseFinanziarie]
      ,[IdReportPDFDiagnosi]
      ,[IdReportPDFMonitoraggio]
	  ,scaduto
	  )
SELECT 
 DISTINCT
                    contratti.Cod_Fiscale as i_CodiceFiscale
                    ,contratti.Rete as i_Rete
                    --DATI COMUNI
                    --RETE
                    ,contratti.Rete
                    ,CASE WHEN UPPER(contratti.Rete) = 'F' THEN 'Fideuram' ELSE 'Sanpaolo Invest' END NomeRete
                    --AGENTE     
                    ,contratti.Cod_Agente Agente
                    ,(CASE UPPER(ISNULL(promotori.STATO,'')) WHEN 'ATTIVO' THEN isnull(promotori.Cognome,'') ELSE '' END) CognomeAgente
                    ,(CASE UPPER(ISNULL(promotori.STATO,'')) WHEN 'ATTIVO' THEN isnull(promotori.Nome,'') ELSE '' END) NomeAgente
                    ,isnull(promotori.Indirizzo,'') IndirizzoAgente
                    ,isnull(promotori.Cap,'') CapAgente
                    ,isnull(promotori.Localita,'') CittaAgente
                    ,isnull(promotori.TEL_Recapito,'') TelefonoAgente
                    --CLIENTE
                    ,contratti.Cod_Fiscale CodiceFiscale
                    ,clienti.Cognome CognomeCliente
                    ,clienti.nome NomeCliente
                    --PATRIMONI CLIENTE
                    ,CASE WHEN isnull( MIFID.SCADUTO,1) = 1 THEN 0 ELSE 1 END ProfiloIsAct
                   ,isnull(PatrNonRapprAsset.Controvalore,0) as PatrimonioNonRappresentabile
                    ,isnull(patrimonioBF.PartiteViaggiantiDisinv,0) as PartiteViaggiantiDisinv
                    ,isnull(partiteViaggianti.Importo,0) as PartiteViaggiantiInv
                    ,isnull(patrimonioBF.ContoCorrente,0) as  ContoCorrente
                    ,isnull(patrimonioBF.PatrimonioSenzaCC,0) as PatrimonioBancaFideuramCtvAlNettoContoCorrente 
                    ,isnull(patrimonioBF.PatrimonioNonAssociato,0) as  RisorseNonAssociate
                    ,isnull(patrimonioAltro.Patrimonioaltro,0) as Patrimonioaltroctv
                    ,isnull(patrimonioImmobiliare.PatrimonioImmob,0) as Patrimonioimmobiliarectv
                    ,isnull(patrimonioTerzi.ctv,0) as PatrimonioTerzictv
                    ,isnull(patrimonioTerzi.ControvaloreSenzaCC,0) as PatrimonioTerziCtvAlNettoContoCorrente 
                    ,isnull(patrimonioTerzi.ControvaloreCC,0) as PatrimonioTerziContoCorrente
                    ,isnull(patrimonioBF.ctv,0) as Patrimoniobancafideuramctv
                    ,(isnull(patrimonioBF.ctv,0) + isnull(patrimonioTerzi.ctv,0)) as Patrimoniocomplessivototalectv
                    ,isnull(numIntermediari.NumeroIntermediari,0) as NumeroIntermediari
                    --CONTRATTO
                    ,contratti.CodiceContratto CodiceContratto
                    ,contratti.tip_contratto AS tip_contratto 
                    ,0 AS contrattoold
                    --*************************************************
                    ,ISNULL(monit.NoMonitoraggio, 1) AS NoMonitoraggio --fix 20161012
                    ,'Diagnosi' as descrizioneDiagnosi
                    ,CASE 
                           WHEN contratti.freq_Diagnosi is not null AND contratti.tip_contratto = 0 THEN 5
                           ELSE -1
                    END AS idModelloDiagnosi
                    ,CASE 
                           WHEN contratti.freq_Diagnosi is not null AND contratti.tip_contratto = 0 THEN 1
                           ELSE -1
                    END AS idReportDiagnosi
                    ,'Monitoraggio' as descrizioneMonitoraggio
                    ,4 as idReportMonitoraggio--4
                    ,CASE isnull(tip_contratto,0) 
                                 WHEN 0 THEN 12--12
                                 WHEN 1 THEN 12--12
                                 WHEN 2 THEN 13--13
                    END AS idModelloMonitoraggio
                    --*************************************************
             ,0 AS AdesioneSuccessivaAvanzato
                    ,CASE 
                           WHEN RISCHIO_NA.VAR_PERC_PTF IS NULL THEN -1000
                           ELSE RISCHIO_NA.VAR_PERC_PTF 
                    END AS VaRRisorseNonAssociate    
                    ,CASE 
                           WHEN RISCHIO_NA.COPERTURA IS NULL THEN -1000
                           ELSE RISCHIO_NA.COPERTURA
                    END AS CoperturaRisorseNonAssociate
                    ,CASE 
                           WHEN RISCHIO_RISORSEFINANZIARIE.VAR_PERC_PTF IS NULL THEN -1000
                           ELSE RISCHIO_RISORSEFINANZIARIE.VAR_PERC_PTF 
                    END AS VaRTotaleRisorseFinanziarie
                    ,CASE 
                           WHEN RISCHIO_NA.COPERTURA IS NULL THEN -1000
                           ELSE RISCHIO_RISORSEFINANZIARIE.COPERTURA
                    END AS CoperturaTotaleRisorseFinanziarie
                    ,isnull((SELECT max(idReport) FROM c6martperiodico.GESTIONE_PDF_FTP ftp where tipoReport = 'D' 
                                 AND ftp.codicefiscale = contratti.cod_fiscale AND ftp.rete = contratti.Rete),0)  
                    AS IdReportPDFDiagnosi   
                    ,isnull((SELECT max(idReport) FROM c6martperiodico.GESTIONE_PDF_FTP ftp where tipoReport = 'M' 
                                 AND ftp.codicefiscale = contratti.cod_fiscale AND ftp.rete = contratti.Rete),0) 
                    AS IdReportPDFMonitoraggio 
                    ,mifid.scaduto
             FROM  [C6MartPeriodico].contrattoSEI contratti
             left outer join [C6MartPeriodico].ANAG_PROMOTORI promotori
                    on contratti.Rete = promotori.Rete
                    and contratti.Cod_Agente = promotori.Id_Promotore
                    --65992
             inner join [C6MartPeriodico].ANAG_CLIENTI clienti
                    on contratti.Rete = clienti.Rete
                    and contratti.Cod_Fiscale = clienti.Cod_Fiscale
             --V non stampo se non ha patrimonio
             inner join [C6MartPeriodico].vPatrimoniobfAggregato patrimonioBF
                    on contratti.Rete = patrimonioBF.Rete
                    and contratti.Cod_Fiscale = patrimonioBF.Cod_Fiscale 
                    -- 64864
             left outer join [C6Mart].vPatrimonioAltroAggregato patrimonioAltro
                    on contratti.Rete = patrimonioAltro.Rete
                    and contratti.Cod_Fiscale = patrimonioAltro.Cod_Fiscale 
                    --64864
             left outer join [C6MartPeriodico].vPatrimonioImmobAggregato patrimonioImmobiliare
                    on contratti.Rete = patrimonioImmobiliare.Rete
                    and contratti.Cod_Fiscale = patrimonioImmobiliare.Cod_Fiscale 
             left outer join [C6MartPeriodico].vPatrimonioTerziAggregato patrimonioTerzi
                    on contratti.Rete = patrimonioTerzi.Rete
                    and contratti.Cod_Fiscale = patrimonioTerzi.Cod_Fiscale
                    --64864
             left outer join [C6MartPeriodico].MIFID MIFID
                    on contratti.Rete = MIFID.Rete
                    and contratti.Cod_Fiscale = MIFID.Cod_Fiscale
             left outer join [C6MartPeriodico].vPatrimonioNonRappresentabileAsset PatrNonRapprAsset
                    on contratti.Rete = PatrNonRapprAsset.Rete
                    and contratti.Cod_Fiscale = PatrNonRapprAsset.Cod_Fiscale
             left outer join [C6MartPeriodico].vNumeroIntermediari numIntermediari
                    on contratti.Rete = numIntermediari.Rete 
                    and contratti.Cod_Fiscale = numIntermediari.Cod_Fiscale
                    --64864
             left outer join [C6MartPeriodico].RISCHIO_AGGREGATO RISCHIO_NA
                    on contratti.Rete = RISCHIO_NA.Rete 
                    and contratti.Cod_Fiscale = RISCHIO_NA.Cod_Fiscale
                    and RISCHIO_NA.cod_aggreg = 'COMPLESSIVO|BF|NA'
                    --modificata da Valerio 12 marzo 2012
                    --left outer join [C6MartPeriodico].RISCHIO_AGGREGATO RISCHIO_RISORSEFINANZIARIE
             inner join [C6MartPeriodico].RISCHIO_AGGREGATO RISCHIO_RISORSEFINANZIARIE
                    on contratti.Rete = RISCHIO_RISORSEFINANZIARIE.Rete 
                    and contratti.Cod_Fiscale = RISCHIO_RISORSEFINANZIARIE.Cod_Fiscale
                    and RISCHIO_RISORSEFINANZIARIE.cod_aggreg = 'COMPLESSIVO|BF'
                    --64864
             left outer join C6MartPeriodico.PARTITE_VIAGGIANTI PARTITEVIAGGIANTI
                    on contratti.Rete = PARTITEVIAGGIANTI.RETE
                    and contratti.Cod_Fiscale = PARTITEVIAGGIANTI.COD_FISCALE
                    --64864
             left join (
                    select distinct monit.rete, monit.cod_fiscale, 
                           case when isnull(monitInit.data_foto,getDate()) >= c6martperiodico.getPreviousTrimestre(getDate(),0) then 1 
                           when monitReport.cod_fiscale is null then 1 else 0 end as NoMonitoraggio
                    from c6martperiodico.monitoraggio_attuale monit
                           left join c6martperiodico.monitoraggio_iniziale monitInit on monit.rete = monitInit.rete and monit.cod_fiscale = monitInit.cod_fiscale
                           left join c6martperiodico.monitoraggio_report monitReport on monit.rete = monitReport.rete   and monit.cod_fiscale = monitReport.cod_fiscale
                    ) monit
                    on patrimonioBF.rete = monit.rete
                    and patrimonioBF.cod_fiscale = monit.cod_fiscale     
             WHERE 1=1
             --144104
		end	
-------------------------------------------------------------------------
END