-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--[C6MartPeriodico].[PL_S56PatrimonioBFAreeBisogno] 'F','TNNLGU58R01B259Y'
CREATE procedure [C6MartPeriodico].[PL_S56PatrimonioBFAreeBisogno]
	-- Add the parameters for the stored procedure here
	@Rete char(1), 
	@CodiceFiscale varchar(16)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SELECT		
		AREA_BISOGNO.ID_AREA AS NeedArea,
		AREA_BISOGNO.NOME_AREA AS AreaName,
		COALESCE(PIRAMIDE_VERT.CTV_AREA, 0.00) AS ControValore,
		COALESCE(
			CAST(100*(PIRAMIDE_VERT.CTV_AREA / 
			SUM(COALESCE(PIRAMIDE_VERT.CTV_AREA,0)) OVER (PARTITION BY PIRAMIDE_VERT.RETE, PIRAMIDE_VERT.COD_FISCALE)) AS DECIMAL(5,2))
			, 0.00) AS Peso,
		COALESCE(RISCHIO_AGGREGATO.VAR_PERC_PTF, 0.00) AS Var_NeedArea,
		NULL AS Var_NeedAreaString,
		COALESCE(RISCHIO_AGGREGATO.COPERTURA, 0) AS Copertura_NeedArea,
		CASE 
			WHEN RISCHIO_AGGREGATO.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISCHIO_AGGREGATO.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS Copertura_NeedAreaString,
		NULL AS RischioRelativo, -- TODO: CHIEDERE
		NULL AS Nota, -- TODO: CHIEDERE
		SUM(COALESCE(PIRAMIDE_VERT.CTV_AREA,0)) OVER (PARTITION BY 'Totale') AS Somma_Controval,
		RISCHIO_TOTALE.VAR_PERC_PTF AS Var_tot,
		RISCHIO_TOTALE.COPERTURA AS Copertura_tot,
		CASE 
			WHEN RISCHIO_TOTALE.COPERTURA IS NULL THEN 'n.c.' 
			WHEN RISCHIO_TOTALE.COPERTURA = 0 THEN 'n.c.' 
			ELSE NULL 
		END AS Copertura_totString
	FROM C6MartPeriodico.AREA_BISOGNO
	LEFT JOIN (
		-- GROUP BY PER ACCORPARE I CTV_AREA SULLE PRE1 E PRE2 IN UNO UNICO CORRISPONDENTE A PRE
		SELECT RETE, COD_FISCALE, LEFT(ID_AREA,3) AS ID_AREA, SUM(COALESCE(CTV_AREA,0)) AS CTV_AREA
		FROM C6MartPeriodico.PIRAMIDE_VERT 
		WHERE PIRAMIDE_VERT.RETE = @Rete
			AND PIRAMIDE_VERT.COD_FISCALE = @CodiceFiscale
		GROUP BY RETE, COD_FISCALE, LEFT(ID_AREA,3) 
	) PIRAMIDE_VERT ON PIRAMIDE_VERT.ID_AREA = AREA_BISOGNO.ID_AREA
--	LEFT JOIN C6MartPeriodico.PIRAMIDE_VERT
--		ON LEFT(PIRAMIDE_VERT.ID_AREA,3) = AREA_BISOGNO.ID_AREA
--		AND PIRAMIDE_VERT.RETE = @Rete
--		AND PIRAMIDE_VERT.COD_FISCALE = @CodiceFiscale
	LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO 
		ON RISCHIO_AGGREGATO.COD_AGGREG = 'PIRAMIDE|' + LEFT(AREA_BISOGNO.ID_AREA,3)
		AND RISCHIO_AGGREGATO.RETE = @Rete
		AND RISCHIO_AGGREGATO.COD_FISCALE = @CodiceFiscale
	LEFT JOIN C6MartPeriodico.RISCHIO_AGGREGATO AS RISCHIO_TOTALE
		ON RISCHIO_TOTALE.COD_AGGREG = 'PIRAMIDE'
		AND RISCHIO_TOTALE.RETE = @Rete
		AND RISCHIO_TOTALE.COD_FISCALE = @CodiceFiscale
	WHERE  AREA_BISOGNO.ORDINAMENTO < 6 
	ORDER BY AREA_BISOGNO.ORDINAMENTO
END