Follow the command I made and the result
SELECT ATENDIME.CD_ATENDIMENTO, ATENDIME.CD_PACIENTE, PACIENTE.NM_PACIENTE, ATENDIME.DT_ATENDIMENTO, ATENDIME.DT_ALTA,LAG(DT_ALTA,1)OVER (ORDER BY ATENDIME.CD_PACIENTE) AS ULT
FROM ATENDIME
JOIN (SELECT CD_PACIENTE FROM ATENDIME
WHERE CD_LEITO IN (SELECT CD_LEITO FROM LEITO WHERE CD_UNID_INT IN (10,11,18))
GROUP BY CD_PACIENTE HAVING COUNT(CD_PACIENTE)> 1) A
ON A.CD_PACIENTE = ATENDIME.CD_PACIENTE
JOIN PACIENTE ON PACIENTE.CD_PACIENTE = ATENDIME.CD_PACIENTE
WHERE CD_LEITO IN (SELECT CD_LEITO FROM LEITO WHERE CD_UNID_INT IN (10,11,18))
ORDER BY ATENDIME.CD_PACIENTE
From then on I would compare the ULT field with DT_ATENDIMENTO, but it brings the data of other patients, and it is necessary to list only those who had the readmission until 30 days after their discharge
Alexandre, the DT_ATENDIMENTO field is of the date type?
– Filipe L. Constante