CREATE procedure [C6MartPeriodico].[DM_dettaglio_MOV]
AS BEGIN
--INSERT INTO C6MartPeriodico.Dettaglio_MOV
SELECT 
	[RETE],
	CASE 
		WHEN CODMAN ='' 
			THEN CODFIS
			ELSE 'FF@'+CODMAN
		END AS CODFIS,
    sum(APPORTI) - sum(PRELIEVI) as dettaglio
FROM 
	[C6StagingPeriodico].[W6APTR]
WHERE 
	DTTRIM =(select max(dttrim) from [C6StagingPeriodico].[W6APTR])
GROUP BY 
		RETE, 
		CASE WHEN CODMAN ='' THEN CODFIS ELSE 'FF@'+CODMAN END
END