SQL to find family relationship

2020-05-01 08:25发布

Below table structure contains the relationship hierarchy in a family (till level 4 is applicable. e.g. hierarchy can start with 1 and end with 1.4.4.4).

King is first member in family (1) and Jones is his first son (1.1) and Clark is his third son (1.3).

Similarly Allen is King’s second son’s (Blake) first son (1.2.1) and etc.

NAME   | RELATION HIERARCHY 
------ ------------------
King   | 1   
Jones  | 1.1   
Scott  | 1.1.1   
Adams  | 1.1.1.1   
Ford   | 1.1.2   
Smith  | 1.1.2.1   
Blake  | 1.2   
Allen  | 1.2.1   
Ward   | 1.2.2 
Clark  | 1.3 
Miller | 1.3.1     

The challenge is to establish relationship between any two given members in the family. Consider the below output for example.

Member1  | Member2  |Establish Relationship of Member 1 to Member 2  
--------------------------------------------------------------------
Jones    |Allen     |Father's elder brother   
Clark    |Scott     |Father's second younger brother 

I am very new to writing queries.

create function Relation(In Member1 Varchar2(20),In Member2 Varchar2(20))
  as
      Mem1 varchar2(50)
      Mem2 varchar2(50)
      Path varchar2(50)
      T number;

  Begin
    Select rel_Hier into Mem1 from Rel where Name = Member1; 
    Select rel_Hier into Mem2 from Rel where Name = Member2;

  if((substr(Mem1),1,1)=(substr(Mem2),1,1)) /* Checking whether first number is same in both the members */
  Then

    if((substr(Mem1),3,1)=(substr(Mem2),3,1))/* Checking whether third number is same in both the members */
    Then

        if((substr(Mem1),5,1)=(substr(Mem2),5,1)) /* Checking whether fifth number is same in both the members */
        Then

            T := 5;

        End If;
    Else
        T:=3;   

    End If;

  End if;
  path : = reverse(substr(mem1,t))||,||substr(mem2,t);
  find_relation(path);

End;
/

create procedure Find_Relation ( Path varchar2(20))
as
    Sol varchar2(50);
    var1 varchar2(30);
    i number; 

Begin
    i:=0;
    while(i< substr(path,','))
    Loop
        Select relation into var1 from Rel_Tb_Father where id=substr(Path,i,3);
        Sol := Sol ||var1||"'s";
        i:=i+2;
    End Loop

    var1:=Select relation from Rel_Tb_Father where id=substr(Path,substr(path,',')-1,3);
    Sol = Sol ||var1||"'s";

    i:=substr(path,',')+1;
    while(i> substr(path,',') and i<length(path)))
    Loop
        var1:=Select relation from Rel_Tb_Son where id=substr(Path,i,3);
        Sol := Sol ||var1||"'s";
        i:=i+2;
    End Loop

    var1:=Select relation from Rel_Tb_Son where id=substr(Path,length(Path)-3);
    Sol := Sol ||var1||"'s";
    dbms_output.put_line(Sol);

End;
/

I know this wont work because it contains a lot of syntax and logic errors. How to proceed with this code?

标签: sql oracle
0条回答
登录 后发表回答