PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Query SQL:recupera le righe ordinate da una tabella - II

Modificando la risposta alla tua domanda precedente, ottieni quanto segue...

WITH RECURSIVE sub(s_id, s_r_id, s_a_id, s_p_id, row) AS (
    SELECT id, r_id, a_id, p_id, 1 AS row FROM foo WHERE p_id = 0
UNION ALL
    SELECT id, r_id, a_id, p_id, (row + 1)  FROM foo JOIN sub ON s_a_id = p_id AND s_r_id = r_id
)
SELECT * FROM sub ORDER BY s_r_id, row;