What is the equivalent Teradata syntax to answer the same question asked about reverse aggregation inside of common table expression found at Reverse aggregation inside of common table expression?
I am trying to hack a Teradata syntax version to iterate over a parent child relationship table and build JSON which places parent of child who is parent to child who is parent to child etc in the one JSON field.
This is the answer given in the question from the hyperlink listed above which I think is written for PostgreSQL. I would really appreciate assistance in translating this to TD as I think this answer should allow me to accomplish my intended task. If not please set me straight.
I am not sure what row_to_json(c) is calling should this be JSON_AGG(c.children)? and I think that the double colon (NULL::JSON) is casting a null to a JSON data type? In any case I have tried a few variations to no avail. Please help.
Here is the PostgreSQL syntax answer given:
WITH RECURSIVE cte AS (
SELECT id, parent_id, name, NULL::JSON AS children
FROM people p
WHERE NOT EXISTS ( -- only leaf nodes; see link below
SELECT 1 FROM people
WHERE parent_id = p.id
)
UNION ALL
SELECT p.id, p.parent_id, p.name, row_to_json(c) AS children
FROM cte c
JOIN people p ON p.id = c.parent_id
)
SELECT id, name, json_agg(children) AS children
FROM cte
GROUP BY 1, 2;