WITH Query1 AS
(
SELECT DISTINCT
ROW_NUMBER() OVER(PARTITION BY plz ORDER BY geloescht DESC, enddate DESC) As ROWNUM,
...
FROM
(
SELECT m.id,
m.tabelle-x,
m.id-x,
m.plz,
m.geloescht,
x1.enddatum AS enddatum
FROM main m
LEFT JOIN x1 ON m.id-x = x1.id
WHERE m.tabelle-x = 'x1'
UNION ALL
SELECT m.id,
m.tabelle-x,
m.id-x,
m.plz,
m.geloescht,
x2.enddatum AS enddatum
FROM main m
LEFT JOIN x2 ON m.id-x = x2.id
WHERE m.tabelle-x = 'x2'
...
) Tbl1
WHERE
...
)
SELECT
...
FROM
Query1
WHERE
ROWNUM = 1
ORDER BY
...