WITH x AS
(
SELECT ROWNUM seq, id1, flag
FROM (SELECT id1, flag,
CASE flag
WHEN 'F'
THEN 1
WHEN 'M'
THEN 2
ELSE 3
END cntr
FROM a) a,
TABLE (CAST (MULTISET (SELECT cntr + LEVEL - 1
FROM DUAL
CONNECT BY LEVEL <= cntr) AS SYS.odcinumberlist
)
)),
y AS
(SELECT ROWNUM seq, id2
FROM b
ORDER BY id2)
SELECT id1, flag, id2
FROM x, y
WHERE x.seq = y.seq
ORDER BY flag ;