หน้าเว็บ

วันศุกร์ที่ 9 มกราคม พ.ศ. 2558

แก้ปัญหา Oracle SQL LISTAGG not support

LISTAGG เป็น aggregate function ที่เอาไว้ join multiple row ให้เป้น single row  เช่น




ถ้าเรา run SQL นี้ไม่ได้ (เนื่องจาก version ไม่ support)
select gp, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) name
from(
  select 'A' gp, 1 name from dual
  UNION
  select 'A' gp, 2 name from dual
  UNION
  select 'A' gp, 3 name from dual
  UNION
  select 'A' gp, 4 name from dual
   UNION
  select 'B' gp, 5 name from dual
  UNION
  select 'B' gp, 6 name from dual
  UNION
  select 'B' gp, 7 name from dual
  UNION
  select 'B' gp, 8 name from dual
)

group by gp
ลอง run แบบนี้ดูครับ
select gp, RTRIM (XMLAGG (XMLELEMENT (e, name || ', ')).EXTRACT ('//text()'), ', ') name
from(
  select 'A' gp, 1 name from dual
  UNION
  select 'A' gp, 2 name from dual
  UNION
  select 'A' gp, 3 name from dual
  UNION
  select 'A' gp, 4 name from dual
   UNION
  select 'B' gp, 5 name from dual
  UNION
  select 'B' gp, 6 name from dual
  UNION
  select 'B' gp, 7 name from dual
  UNION
  select 'B' gp, 8 name from dual
)

group by gp
ถ้าทำแล้วมันมี string ที่ซ้ำกันแล้วเราต้องการลบตัวที่ซ้ำ ใช้ ตัวนี้ช่วยครับ
...
... /* replace YOUR_STRING */
...
REGEXP_REPLACE(REGEXP_REPLACE(regexp_replace( YOUR_STRING ,'([^,]+)(, \1)+', '\1'),',{2,}',','),'^,|,$','')
...
...
Thank you : http://stackoverflow.com/questions/468990/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-oracle

ไม่มีความคิดเห็น:

แสดงความคิดเห็น