Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse order of a CTE result?

Here’s my code, to traverse all nodes starting from one:

SELECT * INTO MyTable
FROM
(
    SELECT 1 Id, 1 ParentId, 'Parent A' Name
    UNION ALL
    SELECT 5,1,'Child A1'
    UNION ALL
    SELECT 47894,5,'Child A2'
    UNION ALL
    SELECT 2,2, 'Parent B'
    UNION ALL
    SELECT 3,2, 'Child B1'
)TAB

;With CTE as
(
  select * from MyTable where Id = 47894
  union all
  select a.* from MyTable a inner join cte b 
    on a.Id=b.ParentId and a.Id<>b.Id
)

select STRING_AGG(Name, ' >> ') from CTE

With input 47894, it gives:

Child A2 >> Child A1 >> Parent A

What if I need the reverse?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Parent A >> Child A1 >> Child A2

>Solution :

You can use this:

SELECT *
INTO   MyTable
FROM   (
          SELECT
             1 Id,
             1 ParentId,
             'Parent A' Name
          UNION ALL
          SELECT
             5,
             1,
             'Child A1'
          UNION ALL
          SELECT
             47894,
             5,
             'Child A2'
          UNION ALL
          SELECT
             2,
             2,
             'Parent B'
          UNION ALL
          SELECT
             3,
             2,
             'Child B1'
       ) TAB;
WITH CTE
AS (SELECT
          Id,
          ParentId,
          Name,
          CAST(1 AS INT) AS OrderByValue
    FROM  MyTable
    WHERE Id = 47894
    UNION ALL
    SELECT
         a.Id,
         a.ParentId,
         a.Name,
         OrderByValue + 1
    FROM MyTable a
         INNER JOIN CTE b ON a.Id = b.ParentId
                             AND a.Id <> b.Id)
SELECT STRING_AGG(Name, ' >> ')WITHIN GROUP(ORDER BY CTE.OrderByValue DESC)
FROM   CTE;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading