Reputation: 113
I have a table with lots of employment info and I used listagg
to list all employments for each user, each user on a row instead of the max decode route. Using listagg
works but I want to restrict it to just the first 5 for example. Some staff have over 30 employments listed.
select distinct emp.id_Staff,
count (*) as cnt,
LISTAGG (emp.employer_name || '('|| emp.job_title || ')', ', ')
WITHIN GROUP (ORDER BY emp.employer_name) AS Employ_info
from (
SELECT distinct em.id_Staff, em.employer_name,
em.job_title, em_job_status
FROM employment em
where em.job_status = 'Active'
) emp
group by emp.id_Staff
Upvotes: 2
Views: 4296
Reputation: 1269623
You can use row_number()
to enumerate the values. Then use a case
in listagg()
to just take the first five records:
select e.id_Staff,
count(*) as cnt,
listagg(case when seqnum <= 5 then e.employer_name || '('|| e.job_title || ')' end, ', ')
within group (order by e.employer_name) AS Employ_info
from (select e.*,
row_number() over (partition by e.id_staff order by e.id_staff) as seqnum
from (select distinct em.id_Staff, em.employer_name, em.job_title, em_job_status
from employment em
where em.job_status = 'Active'
) e
) e
group by e.id_Staff
Upvotes: 3