Click here to Skip to main content
15,889,851 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I just want to create a query so that it does the same function as listagg in oracle but I dont want to use wm_cocat, lag or lead. My table is-

Emp_id - emp_name - department
1 - alan - 1
2 - bradley - 1
3 - sarah - 2
4 - will 2
5 - bale - 2
6 - doug - 3
7 - hagar - 3
8 - carla - 4
9 - david - 4
10 - vashi - 1

I have a query which is working but I am not quite sure how it work. The query is-

{
SELECT department,
LTRIM(max(SYS_CONNECT_BY_PATH(emp_name,','))
KEEP (DENSE_RANK LAST ORDER BY emp_name),',')AS employees
FROM (SELECT department,
emp_name,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY emp_name) AS emp,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY emp_name) -1 AS prev
FROM employee4)
GROUP BY department
CONNECT BY department=prior department AND prev = PRIOR emp
START WITH emp = 1; }

Can anyone explain me how this query works and is their any alternative solution for that?
Posted
Updated 11-Aug-15 3:28am
v2

1 solution

WITH COMMON TABLE EXPRESSION we can do something like this-

SQL
with t (emp_name, department, rn) as ( select emp_name, department,row_number()
over (partition by department order by emp_name) as rn
        from employee8),
        c (emp_name, department, rn) as (select  emp_name,department, rn from t where rn = 1
        union all
        select (c1.emp_name) ||', '|| t1.emp_name, t1.department, c1.rn+1
        from t t1 , c c1
        where t1.department = c1.department
          and c1.rn + 1 = t1.rn
)
select emp_name, department
from c c1
where rn = (select max(rn)
            from c c2
            where c1.department = c2.department)
            order by department;



By using dense_rank and rownumber we can do it like-

SQL
with t (emp_name, department, rn) as ( select emp_name, department,row_number()
over (partition by department order by emp_name) as rn
        from employee8),
        c (emp_name, department, rn) as (select  emp_name,department, rn from t where rn = 1
        union all
        select (c1.emp_name) ||', '|| t1.emp_name, t1.department, c1.rn+1
        from t t1 , c c1
        where t1.department = c1.department
          and c1.rn + 1 = t1.rn
)
select emp_name, department
from c c1
where rn = (select max(rn)
            from c c2
            where c1.department = c2.department)
            order by department;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900