How to make a select where the order "Group" is shown after "Child Groups"

Asked

Viewed 45 times

1

As it is a system that contains registration of Product Groups. I want to know how to make a select that brings me the information in the following order inside SQL and ordering everything alphabetically.

Summary: Lists a Group, then the Children Groups. Lists the next Group and below, its Children Groups.

EX:

  • DRINKS (would be the Parent Group)
  • SOFT DRINKS (would be the Grupo Filho);
  • ÁGUAS (would be Grupo Filho);
  • BEERS (would be the Son Group);
  • LANCHES (would be the Parent Group)
  • XIS (would be the Son Group);
  • HOT DOG (would be the Son Group);

Table Grupoproduct grpDescGroup column

  • I think you need to post more information about the structure of your table, among them, how it is possible to identify the father’s children

  • Table: Groupproduct & #Xa;I use the columns: idGrupoProduct (PK), grpDescGroup, grpGroupProduct (FK - of the Groupproduct). I want to do a query where I can organize the contents from within that table. OBS: organizing everything alphabetically. Hence would be in the first line: DRINKS (would be the Parent Group) In the second line: WATERS (would be the Son Group); In the third line: BEERS (would be the Son Group); In the fourth line: SOFT DRINKS (would be the Son Group); But in the same table, also lists the other groups and their children as well.

  • Is there a limit to the amount of levels? A Child Group can be a parent?

  • Yes, in levels it would be. Father (Group) - Son (Subgroup) and at most one more son (Subgroup of the 1st Subgroup). That is, finishing in the 3rd level.

1 answer

1


Here is a suggested test using a recursive CTE:

with CTE_Rec as
(
  select
    idGrupoProduto, 
    grpDescGrupo, 
    grpGrupoProdutoPai,
    cast(grpDescGrupo as varchar(1000)) as DescOrdem
  from GrupoProduto
  where grpGrupoProdutoPai is null
  
  union all
  
  select
    g.idGrupoProduto, 
    g.grpDescGrupo, 
    g.grpGrupoProdutoPai,
    cast(c.grpDescGrupo + '|' + g.grpDescGrupo as varchar(1000))
  from CTE_Rec as c
  inner join GrupoProduto as g
    on g.grpGrupoProdutoPai = c.idGrupoProduto
)

select * from CTE_Rec
order by DescOrdem

I hope it helps

  • Dude, that’s exactly what it was. I did it differently here, creating 3 views to get the same result. I made one to separate the Parent Group, another to take only the children and then put it together, it was laborious, but it also worked. But that’s right, as I’m still learning, I came here to seek other solutions, thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.