ALTER PROCEDURE [dbo].[sp_remPagoImposicionesMutualidad]
(
	@PERIODO INT = 0,
	@MES INT = 0,
	@ficini INT = 0,
	@ficfin INT = 0,
	@unineg INT = 0,
	@DEP INT = 0,
	@SEC INT = 0
)
AS
BEGIN

	SELECT 
		T.ficha,
		T.rut, T.dv, T.apePaterno, T.apeMaterno, T.nombres, 
		dbo.remValorResultado(T.periodo,T.mes,T.ficha, 36) AS  'Remuneracion Imponible'
	INTO #MUT
	FROM
		remTrabajadores AS T
	WHERE T.periodo = @PERIODO 
		AND	T.mes = @MES
		AND	(T.ficha BETWEEN @ficini AND @ficfin)
		AND (@unineg = 0 or T.unidadNegocios = @unineg) 
		AND	(@DEP = 0 or T.departamento = @DEP)
		AND (@SEC = 0 or T.seccion = @SEC)
		AND	T.activo = 1
		ORDER BY T.apePaterno,
			T.apeMaterno

	
	SELECT 
		T.ficha,
		ISNULL (MP.codMovimiento, 0) AS Codigo,
		ISNULL (MP.fechaInicio, '') AS FechaIni,
		ISNULL (MP.fechaTermino, '') AS FechaFin
	INTO #MOV
	FROM
		remMovPersonal AS MP JOIN remTrabajadores AS T
		ON MP.periodo = T.periodo AND MP.mes = T.mes AND MP.ficha = T.ficha
	WHERE T.periodo = @PERIODO
		AND T.mes = @MES
		AND (T.ficha BETWEEN @ficini AND @ficfin)
		AND (@unineg = 0 or T.unidadNegocios = @unineg) 
		AND	(@DEP = 0 or T.departamento = @DEP)
		AND (@SEC = 0 or T.seccion = @SEC)
		AND T.activo = 1

	--SELECT * FROM #MUT AS MU INNER JOIN #MOV AS M ON MU.ficha = M.ficha 

	SELECT
		ROW_NUMBER() OVER(PARTITION BY F.ficha ORDER BY F.ficha)as numlin,
		1 AS validador,
		F.ficha,
		F.rut,
		F.dv,
		F.apePaterno,
		F.apeMaterno,
		F.nombres,
		F.[Remuneracion Imponible],
		ISNULL (M.codigo, 0) AS Codigo,
		ISNULL (M.FechaIni, '') AS FechaIni,
		ISNULL (M.FechaFin, '') AS FechaFin
	INTO #TOP
	FROM #MUT AS F LEFT OUTER JOIN #MOV AS M ON F.ficha = M.ficha

	UNION ALL

	SELECT
		ROW_NUMBER() OVER(PARTITION BY F.ficha ORDER BY F.ficha)as numlin,
		0 AS validador,
		F.ficha,
		F.rut,
		F.dv,
		F.apePaterno,
		F.apeMaterno,
		F.nombres,
		0 AS [Remuneracion Imponible],
		ISNULL (M.codigo, 0) AS Codigo,
		ISNULL (M.FechaIni, '') AS FechaIni,
		ISNULL (M.FechaFin, '') AS FechaFin
	FROM #MUT AS F LEFT OUTER JOIN #MOV AS M ON F.ficha = M.ficha

	SELECT *  FROM #TOP 
	WHERE (validador= 0 AND numlin > 1) OR (validador = 1 AND numlin = 1)
	ORDER BY #TOP.apePaterno, #TOP.apeMaterno, #TOP.[Remuneracion Imponible] DESC
END