CREATE procedure [C6Mart].[PL_D2_S163PatrimonioFinanziarioMAssetClass_NEW_20160908] 
( @Rete char(1), 
       @CodiceFiscale varchar(16)
       )as
       begin
       SELECT DISTINCT
             ASSETCLASS.ORDINAMENTO AS Ordinamento,
             VALORIASSET.ID_ASSETCLASS AS AssetClassId, 
             ASSETCLASS.DESCRIZIONE AS AssetClassName, 
             cast(SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS) as decimal(19,6)) AS Controvalore,
             (
             case when SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE') = 0 then 0 else
                    SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY VALORIASSET.ID_ASSETCLASS) /
                    SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE')
                    end
             ) * 100 AS Percentuale,
             cast (SUM(VALORIASSET.CONTROVALORE) OVER (PARTITION BY 'TOTALE') as decimal(19,6)) AS PatrimonioFinanziarioCTV
       FROM (
             --PRODOTTI TERZI A CATALOGO
             SELECT       
                    ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') AS ID_ASSETCLASS,
                    PATRTERZI.CTV * ISNULL(ASSETPERC.PERC,1) AS Controvalore
             FROM 
                    C6MART.PATRIMONIO_TERZI PATRTERZI
             LEFT OUTER JOIN 
                    C6MART.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'
                    AND PATRTERZI.RETE = @Rete
                    AND PATRTERZI.COD_FISCALE = @CodiceFiscale
             UNION ALL
             --PRODOTTI TERZI NON A CATALOGO
             SELECT 
                    ISNULL(ASSETPERC.ID_ASSETCLASS,'AL') AS ID_ASSETCLASS,
                    PATRTERZI.CTV*ISNULL(ASSETPERC.PERC,1) AS Controvalore
             FROM 
                    C6MART.PATRIMONIO_TERZI PATRTERZI
             LEFT OUTER JOIN 
                    C6MART.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'
                    AND PATRTERZI.RETE = @Rete
                    AND PATRTERZI.COD_FISCALE = @CodiceFiscale
       ) VALORIASSET
       INNER JOIN C6MART.ASSETCLASS ASSETCLASS
             ON 
                    ASSETCLASS.ID_ASSETCLASS = VALORIASSET.ID_ASSETCLASS
       ORDER BY 
             ASSETCLASS.ORDINAMENTO
END