LISTAGG() 函数在oracle11g中才出现,才能使用。
teacher_id | student_id | student_name |
T001 | S001 | Amui |
T002 | S002 | Lily |
T003 | S003 | Lucy |
T002 | S004 | Mark |
T001 | S005 | Linda |
T002 | S006 | Tom |
t_people
-----------------------------------------------------
SELECT tp.teacher_id teacher_id,
LISTAGG(tp.student_id,',') WITHIN GROUP (ORDER BY tp.student_id) AS student_ids
FROM t_people tp
GROUP BY tp.teacher_id
--------------------------------------------------
LISTAGG(tp.student_id,',') 中,第一个参数是所要由列转为行的值,第二个参数','表示用逗号分隔开该列的每个值。可以自定义该符号。
GROUP BY tp.teacher_id 表示:按teacher_id 对所要查找的列值进行分组。listagg() 函数就是将该语句所形成的分组中的每一组的值拼成字符串。
---------------------------------------------------
结果如下:
teacher_id | student_ids |
T001 | S001,S005 |
T002 | S002,S004,S006 |
T003 | S003 |