Search code examples
sqlsnowflake-cloud-data-platformqliksense

Getting different Hierarchy levels and Path in Snowflake SQL


I am trying to replicate the result of a qlik function called Hierarchy. It creates the Hierarchy with different Levels and also gives the Hierarchy Path. The Code that i am using so far is giving me the Levels but with an error that Level2 values are also coming in Level1.

CREATE OR REPLACE TRANSIENT TABLE "Hierarchy" ( "NodeID" VARCHAR, "ParentID" VARCHAR, "NodeName" String)

Insert into "Hierarchy"("NodeID", "ParentID","NodeName")

VALUES
('1','4','London'),
('2','3','Munich'),
('3','5','Germany'),
('4','5','UK'),
('5','',  'Europe');


with recursive CteTree as

(Select "NodeID","ParentID","NodeName" as "NodeName1",

                 CAST (NULL AS varchar(255)) as "NodeName2",
                 CAST (NULL AS varchar(255)) as "NodeName3",
                 0 as NodeName
                 from "Hierarchy"
                 Where "ParentID" is not null

                 UNION ALL

                 Select child."NodeID", child."ParentID", "NodeName1",
                 Case When NodeName+1 = 1 then "NodeName" else "NodeName2" end,
                 Case When NodeName+1 = 2 then "NodeName" else "NodeName3" end,
                 NodeName+1
                 from CteTree

                 Join "Hierarchy" child
                 ON child."ParentID" = CteTree."NodeID"

)

select distinct * from CteTree order by "NodeName1" 

The Output that it is producing: Output from Script

Desired OutPut:

Desired Output

How can it be achieved?


Solution

  • enter image description here

    with Hierarchy (NodeID, ParentID,NodeName) as (select * from VALUES
     ('1','4','London'),
     ('2','3','Munich'),
     ('3','5','Germany'),
     ('4','5','UK'),
     ('5','',  'Europe'))   
                                                                  
     select   
         sys_connect_by_path(NodeName, ' -> ') path 
        , NodeID
        , ParentID
        , NodeName  
     from 
          Hierarchy 
     START WITH ParentID ='' 
     CONNECT BY PRIOR NodeID =  ParentID ;
    

    enter image description here

    enter image description here