Help in Tree Mapping query

Kenny Gua 411 Reputation points
2023-01-19T02:02:54.4366667+00:00

Hello- I want to search the Expcode of 'ST' for Maintree-'RD' only. I want to see all Expcode which is mapped related with 'ST'. If you see ExpCode-ST, it is mapped with 'DT'

if you see ExpCode-DT is mapped with 'DN'

if you see ExpCode-DN is mapped with 'DD'

Create table ERT (MainTree char(10), ExpCode char(4), MapCode char(4), Edate datetime)

Insert into ERT values ('RD','ST','DT','2020-01-01')

Insert into ERT values ('RD','DT','DN','2020-01-01')

Insert into ERT values ('RD','DN','DD','2020-01-01')

Insert into ERT values ('RD','DD', NULL,'2020-01-01')

So I want to see the following result from query -

Criteria - I want to see all Expcode which is mapped/related with Expcode-'ST'. Bascially I want to see all tree of Expcode-ST.

Maintree ExpCode MapCode Edate

RD DD NULL 2020-01-01

RD DT DN 2020-01-01

RD DN DD 2020-01-01

RD ST DT 2020-01-01

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,645 questions
0 comments No comments
{count} votes

Accepted answer
  1. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-01-19T03:05:33.0933333+00:00

    Hi @Kenny Gua

    If I understand correctly, what you need is a recursive query.

    ;with CTE as(
      select * from ERT where ExpCode = 'ST'
      union all
      select A.* from ERT as A inner join CTE as B
      on A.ExpCode = B.MapCode)
    select * from CTE;
    

    Since there is something in your description that confuses me, I'm not sure if this is what you want, and if that's not what you want, please comment.

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2023-01-19T05:51:54.8466667+00:00

    Try this:

    
    ;with CTE as(
      select MainTree, ExpCode, MapCode , Edate,   ExpCode   as pExpCode ,0 as lvl
      from ERT where ExpCode = 'ST'
      union all
      select A.*,  b.pExpCode ,lvl+1 as lvl from ERT as A inner join CTE as B
      on A.ExpCode = B.MapCode)
    select * from CTE
    where pExpCode='ST'
    order by lvl desc;
    
    1 person found this answer helpful.