views:

70

answers:

4

For example, I have this table:

CREATE TABLE perarea
  (
     id_area      INT primary key,
     nombre       VARCHAR2(200),
     id_areapadre INT references perarea(id_area)
  );

Instead of showing:

1 IT null
2 Recursos Humanos null
3 Contabilidad 2
4 Legal 2

I want:

1 IT 
2 Recursos Humanos 
3 Contabilidad Recursos Humanos
4 Legal Recursos Humanos

Any help?

I can't for the life of me figure out how this select would be.

Edit:

This SQL Query works, but doesn't pull the NAME, only the ID of the parent. Any help?

select * from PerArea
connect by id_area = id_areapadre;
+2  A: 

Looks like you want a hierarchical query:

select id_area, nombre, sys_connect_by_path(nombre,'/')
  from perarea
  start with id_areapadre is null
  connect by id_areapadre = prior id_area
  order by id_area
Dave Costa
This works! But how can I have the Parent only show "Recursos Humanos", intead of "/Recursos Humanos/Servicios Al Empleado"? Thanks!
Sergio Tapia
Just replace the '/' character then substr the result to subtract the length of the current nombre
Gary
+4  A: 

For reference, you could also do it without hierarchical extensions by using a self-join:

SELECT p1.id_area, p1.name, COALESCE(p2.name, '')
FROM perarea p1
     LEFT JOIN perarea p2 ON (p1.id_areapadre = p2.id_area)
Justin K
A: 

are you looking for the rootname (CONNECT_BY_ROOT) or the substring path of taking out the "parents" name?

 SELECT id_area, 
           nombre, 
           PATHLEVEL , 
           SUBSTR(PATHLEVEL,INSTR(PATHLEVEL,'/',-1,2)+1, INSTR(PATHLEVEL,'/',-1)-INSTR(PATHLEVEL,'/',-1,2)-1) PARENTNAME ,
           rootNAME
    FROM(
    select id_area, nombre, sys_connect_by_path(nombre,'/')  PATHLEVEL,
           CONNECT_BY_ROOT nombre rootNAME,
      from perarea
      start with id_areapadre is null
      connect by id_areapadre = prior id_area
      order by id_area
    );
tanging
+1  A: 

Hi Sergio,

this is a good example of a hierarchical query. A simple solution with a CONNECT BY:

SQL> SELECT id_area, nombre, PRIOR (nombre)
  2    FROM perarea
  3  CONNECT BY PRIOR (id_area) = id_areapadre
  4   START WITH id_areapadre IS NULL;

 ID_AREA NOMBRE            PRIOR(NOMBRE)
-------- ----------------- -----------------
       1 IT                
       2 Recursos Humanos  
       3 Contabilidad      Recursos Humanos
       4 Legal             Recursos Humanos
Vincent Malgrat