0
select distinct tbl2.id, tbl1.year
from table1 tbl1 join table2 tbl2
on(tbl1.tbl2id = tbl2.id)

here's the output of this query

ID     YEAR    
1      2001   
1      2002    
2      1995   
2      1996

but the output that I want is something like this

1 - 2001, 2002     
2 - 1995, 1996

2 Answers 2

3

Without using cursors and PLSQL, you can use a LISTAGG:

select id || ' - ' || listagg(year, ', ') within group (order by year)
from (
        yourQuery
      )
group by id   
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it as below. First you can use LISTAGG to get the data in a format separated by comma and then run a loop;

Declare

Cursor xyz is 
          select  tbl2.id,listagg(tbl1.year,',') within group (ORDER BY tbl1.id) 
         from table1 tbl1 
          join table2 tbl2
         on tbl1.id = tbl2.id
         group by tbl2.id 
         order by 1 ;

var1 number;    
var2 varchar2(100);

begin

 Open xyz;
 Loop
  fetch xyz into var1, var2;

  EXIT WHEN XYZ%NOTFOUND;

  DBMS_OUTPUT.PUT_LINE('ID-'|| var1 || 'YEAR-' ||var2);

  END Loop;

  close xyz;
End;

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.