SQL “tree-like” query - most parent group

后端 未结 6 1229
悲&欢浪女
悲&欢浪女 2020-12-09 07:22

I\'m having some trouble doing a \"tree-like\" query (what do we call this?) in SQL.

Take a look at my diagram below (table and column names are in danish - sorry ab

6条回答
  •  余生分开走
    2020-12-09 07:52

    I came up with a solution that solves the problem of listing ALL the groups for each customer. Parent and child groups.

    What do you think?

    WITH GroupTree
    AS
    (
        SELECT kg.KundeId, g.Id GruppeId
        FROM ActiveDirectory.Gruppe g
        INNER JOIN ActiveDirectory.Kunde_Gruppe kg ON g.Id = kg.GruppeId
        AND (EXISTS (SELECT * FROM ActiveDirectory.Gruppe_Gruppe WHERE ParentGruppeId = g.Id)
        OR NOT EXISTS (SELECT * FROM ActiveDirectory.Gruppe_Gruppe WHERE ParentGruppeId = g.Id))
    
        UNION ALL
    
        SELECT GroupTree.KundeId, gg.ChildGruppeId
        FROM ActiveDirectory.Gruppe_Gruppe gg
        INNER JOIN GroupTree ON gg.ParentGruppeId = GroupTree.GruppeId
    )
    SELECT KundeId, GruppeId
    FROM GroupTree
    
    OPTION (MAXRECURSION 32767)
    

提交回复
热议问题