WITH q (referencia, statusposto, numposto) AS ( SELECT referencia, posto1, 1 FROM tabela WHERE posto1 IS NOT NULL AND posto1 <> '' UNION SELECT referencia, posto2, 2 FROM tabela WHERE posto2 IS NOT NULL AND posto2 <> '' UNION ... UNION SELECT referencia, posto10, 10 FROM tabela WHERE posto10 IS NOT NULL AND posto2 <> '' ) SELECT q.referencia, q.numposto, q.statusposto FROM q JOIN ( SELECT q.referencia, MAX(q.numposto) maiorposto FROM q GROUP BY q.referencia) r ON r.referencia = q.referencia AND r.maiorposto = q.numposto