Good morning Tony,
tries to do this, making a group by the code
Select all
SELECT x.codigo,
min(x.dtini) dtini,
max(x.dtfim) dtfim,
from (
SELECT T.NUMFUNC,
T.NUMVINC,
t.dtini,
t.dtfim,
t.codigo
FROM (SELECT L.NUMFUNC, L.NUMVINC,
--
(CASE WHEN L.DTINI <=to_date('01/01/2016','dd/mm/yyyy') THEN
to_date('01/01/2016','dd/mm/yyyy')
ELSE
L.DTINI
END) DTINI,
--
( CASE WHEN (L.DTFIM >=LAST_DAY(to_date('01/12/2016','dd/mm/yyyy')) OR L.DTFIM IS NULL) THEN
to_date('31/12/2016','dd/mm/yyyy')
ELSE
L.DTFIM
END) DTFIM, I.ITEM CODIGO
--
FROM ITEMTABELA I, LIC_AFAST L, CODIGOS_FREQ_ F, VINCULOS V
WHERE L.NUMFUNC= 381454 --WNUMFUNC
AND L.NUMVINC = 1 --WNUMVINC
AND L.CODFREQ = F.CODIGO
AND L.NUMFUNC = V.NUMFUNC
AND L.NUMVINC = V.NUMERO
AND ((TO_CHAR(L.DTINI,'YYYY')='2016' OR TO_CHAR(L.DTFIM,'YYYY')='2016') or
(L.DTFIM IS NULL AND TO_CHAR(L.DTINI,'YYYY')<='2016') OR
(TO_CHAR(L.DTINI,'YYYY') <='2016' AND TO_CHAR(L.DTFIM,'YYYY') >='2016'))
AND V.EMP_CODIGO = 1 --WEMPRESA
AND I.ITEM = F.FLEX_CAMPO_03
AND NVL(V.FORMAVAC,' ') <> 'EXCLUSAO'
AND I.TAB = 'RAIS_AFASTAMENTO_MTE'
AND V.DTEXERC = '02/05/2007'--PDTEXERC
AND I.ITEM > 0) T
GROUP BY T.NUMFUNC, T.NUMVINC,t.dtini, t.dtfim, t.codigo) x
group by x.codigo
order by 1
In this test I'm neglecting numfunc and numvinc, just to see if there is a more or less correct result ...