Friday, August 14, 2015

Limit the number of list entries that listagg will consume.

SQL> select student_name, course_id from studentx order by student_name

STUDENT_NAME COURSE_ID
------------ ---------
Chris Jones  A102     
Chris Jones  C102     
Chris Jones  C102     
Chris Jones  A102     
Chris Jones  A103     
Chris Jones  A103     
Joe Rogers   B103     
Joe Rogers   A222     
Joe Rogers   A222     
Kathy Smith  B102     
Kathy Smith  A102     
Kathy Smith  A103     
Kathy Smith  B102     
Kathy Smith  A103     
Kathy Smith  A102     
Mark Robert  B103     

16 rows selected.
SQL> WITH x AS
        (SELECT student_name,
                course_id,
                ROW_NUMBER () OVER (PARTITION BY student_name ORDER BY 1) AS grouprownum
           FROM studentx)
  SELECT student_name,
         LISTAGG (CASE WHEN grouprownum < 5 THEN course_id ELSE NULL END, ',')
            WITHIN GROUP (ORDER BY student_name)
            courses
    FROM x
GROUP BY student_name

STUDENT_NAME
------------
COURSES                                                                         
--------------------------------------------------------------------------------
Chris Jones 
A102,A102,C102,C102                                                             
                                                                                
Joe Rogers  
A222,A222,B103                                                                  
                                                                                
Kathy Smith 
A102,A103,B102,B102                                                             
                                                                                
Mark Robert 
B103                                                                            
                                                                                

4 rows selected.

2 comments:

Scott Wesley said...

That's rather elegant, I love it. I've been having trouble with this recently and I might give it a go. Stupid 4000 character limit...

Anonymous said...

this so easy solution to max 4000 character, thanks lot

Labels