deeejay

Oracle - LISTAGG Examples

Jan 27th, 2016 (edited)
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ARRAY Aggregate WITH Deduplication
  2. ===
  3. SELECT
  4. REGEXP_REPLACE('00.17,00.40,00.40,00.45,00.66,36.07,37.22,38.97,51.01,88.53,88.56,88.77,93.39,93.83,97.29,97.29,99.04,99.29,99.29'      
  5.     ,'([^,]*)(,\1)+($|,)'
  6.     ,'\1\3')
  7. FROM dual;
  8.  
  9.  
  10. PROCEDURE Example
  11. ===
  12. SELECT FCT_ENCOUNTER.FCT_ENCOUNTER_ID
  13. , REGEXP_REPLACE(
  14.     LISTAGG(DIM_ICD.ICD_CODE, ',') WITHIN GROUP (ORDER BY DIM_ICD.ICD_CODE)
  15.     ,'([^,]*)(,\1)+($|,)'
  16.     ,'\1\3')
  17.     AS ICD_CODE_LISTAGG
  18. FROM EDW.FCT_ENCOUNTER FCT_ENCOUNTER
  19. INNER JOIN EDW.DIM_FACILITY DIM_FACILITY
  20.     ON FCT_ENCOUNTER.FACILITY_ID = DIM_FACILITY.FACILITY_ID
  21. INNER JOIN EDW.FCT_ENCOUNTER_PROCEDURE FCT_ENCOUNTER_PROCEDURE
  22.     ON FCT_ENCOUNTER.FCT_ENCOUNTER_ID = FCT_ENCOUNTER_PROCEDURE.FCT_ENCOUNTER_ID
  23. INNER JOIN EDW.DIM_ICD DIM_ICD
  24.     ON FCT_ENCOUNTER_PROCEDURE.ICD_ID = DIM_ICD.ICD_ID
  25. WHERE 1=1
  26.   AND (DIM_FACILITY.FACILITY_CODE = 'XX'
  27.   AND DIM_FACILITY.STATUS = 'Yes')
  28. GROUP BY FCT_ENCOUNTER.FCT_ENCOUNTER_ID
  29. ;
  30.  
  31. BEFORE:
  32. FCT_ENCOUNTER_ID                ICD_CODE
  33. ===                             ===
  34. 1234567                         00.17
  35. 1234567                         00.40
  36. 1234567                         00.40
  37. 1234567                         00.45
  38. 1234567                         00.66
  39. 1234567                         00.66
  40.  
  41. AFTER:
  42. FCT_ENCOUNTER_ID                ICD_CODE_LISTAGG
  43. ===                             ===
  44. 1234567                         00.17,00.40,00.45,00.66
  45.  
  46.  
  47. LISTAGG USING PARTITION BY
  48. ===
  49.  
  50. SELECT department_id AS "Dept.",
  51.        LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date)
  52.        OVER (PARTITION BY department_id) AS "Employees"
  53.   FROM employees
  54.   ORDER BY department_id;
Advertisement