Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.15 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Oracle: Concat with delimiter, but only if both operands are NOT NULL
  2. select
  3.   a, b, c,
  4.   substr(abc, 1, length(abc) - 1) as abc
  5. from
  6.   (select
  7.     a, b, c,
  8.     nvl2(a, a || ';', '') || nvl2(b, b || ';', '') || nvl2(c, c || ';', '') as abc
  9.   from
  10.     Table1)
  11.        
  12. -- Some sample data, roughly equivalent to yours
  13. with t as (
  14.   select 'foo' as x from dual union all
  15.   select null       from dual union all
  16.   select 'bar'      from dual
  17. )
  18. -- Use the listagg aggregate function to join all values
  19. select listagg(x, ';') within group (order by rownum)
  20. from t;
  21.        
  22. -- I use SYS.ORA_MINING_VARCHAR2_NT as a TABLE TYPE. Use your own, if you prefer
  23. select listagg(column_value, ';') within group (order by rownum)
  24. from table(ORA_MINING_VARCHAR2_NT('foo', null, 'bar'));
  25.        
  26. select listagg(column_value, ';')
  27.        within group (order by rownum)
  28. from Table1
  29. cross join table(ORA_MINING_VARCHAR2_NT(Table1.a, Table1.b, Table1.c))
  30. group by Table1.id;
  31.        
  32. SELECT a
  33. ||     DECODE(b
  34.        ,      NULL, NULL
  35.        ,      ';' || b)
  36. ||     DECODE(c
  37.        ,      NULL, NULL
  38.        ,      ';' || c)
  39. ||     DECODE(d
  40.        ,      NULL, NULL
  41.        ,      ';' || d)
  42. ...
  43. FROM   table1