Oracle listagg去重distinct的三种方式总结

时间:2025-01-22 08:12:58

--第三种方法:先去重,再聚合

select t.department_name depname,

       t.department_key,

       listagg(t.class_key, ',') within group(order by t.class_key) as class_keys

  from (select distinct s.class_key, s.department_key, s.department_name

          from V_YDXG_TEACHER_KNSRDGL s) t

 group by t.department_key, t.department_name

  

--或者

select s.department_key,

       s.department_name,

       listagg(s.class_key, ',') within group(order by s.class_key) as class_keys

  from (select t.department_key,

               t.department_name,

               t.class_key,

               row_number() over(partition by t.department_key, t.department_name, t.class_key order by t.department_key, t.department_name) as rn

          from V_YDXG_TEACHER_KNSRDGL t

         order by t.department_key, t.department_name, t.class_key) s

 where rn = 1

 group by s.department_key, s.department_name;