-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[RP_Popola_PiramideModello]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @datacongelamento as datetime
	declare @dataInizioTrimestre as datetime
	declare @FineTrimestre as datetime
	set @datacongelamento = C6MartPeriodico.getDataCongelamento()
	set @FineTrimestre = C6MartPeriodico.getDataCongelamento()+1
	--convert (date, DATEADD(month, 0, '2020-10-31 00:00:00.000'))
	--Sostituire la data congelamento con la reale data di congelament tramite la funzione già esistente
	set @dataInizioTrimestre = DATEADD(m,-3,DATEADD(mm, DATEDIFF(m,0,@datacongelamento), 0))
	--print @datacongelamento
	--print @FineTrimestre
	--print @dataInizioTrimestre
    -- Insert statements for procedure here
	select Rete,
		   Cod_fiscale,
		   Data_foto
	into #ClientiPiramideIniziale
	from [C6MartPeriodico].[MONITORAGGIO_INIZIALE]
	where data_foto between @dataInizioTrimestre and @FineTrimestre
	--select min(data_foto) from [C6MartPeriodico].[MONITORAGGIO_INIZIALE] where data_foto >= '2020-05-30 00:00:00.000'
	insert into C6StagingPeriodico.Popola_PiramideModello
	select Rete,
		   Cod_fiscale,
		   Data_foto,
		   isnull([C6MartPeriodico].[GetPercentualePiramideMod](cod_fiscale ,RETE ,'Ext'),0.00) as PERC_EXT,
		   isnull([C6MartPeriodico].[GetPercentualePiramideMod](cod_fiscale ,RETE ,'Inv'),0.00) as PERC_INV,
           isnull([C6MartPeriodico].[GetPercentualePiramideMod](cod_fiscale ,RETE ,'Pre'),0.00) as PERC_PRE,
           isnull([C6MartPeriodico].[GetPercentualePiramideMod](cod_fiscale ,RETE ,'Ris'),0.00) as PERC_RIS,
           isnull([C6MartPeriodico].[GetPercentualePiramideMod](cod_fiscale ,RETE ,'Liq'),0.00) as PERC_LIQ
		   from #ClientiPiramideIniziale
		   where rtrim(ltrim(rete))+rtrim(ltrim(cod_fiscale))+rtrim(ltrim(convert(varchar,data_foto,105))) not in 
		   (select distinct(rtrim(ltrim(rete))+rtrim(ltrim(cod_fiscale))+rtrim(ltrim(convert(varchar,data_foto,105)))) from C6StagingPeriodico.Popola_PiramideModello)
		   --and rtrim(ltrim(rete))+rtrim(ltrim(cod_fiscale)) not in 
		   --(select distinct(rtrim(ltrim(rete))+rtrim(ltrim(cod_fiscale))) from C6StagingPeriodico.Popola_PiramideModello)
END