Generate a list from columns that do not contain a zero for each row

oracleselect

I have a table TAB1 in an Oracle database:

+----+----+----+----+----+----+
| ID | C1 | C2 | C3 | C4 | C5 |
+----+----+----+----+----+----+
|  1 |  1 |  0 |  3 |  0 |  5 |
|  2 | 11 | 22 |  0 | 44 |  0 |
+----+----+----+----+----+----+

I need a select statement that gives me the following output:

+----+-------------------------+
| id |          descr          |
+----+-------------------------+
|  1 | column1,column3,column5 |
|  2 | column1,column2,column4 |
+----+-------------------------+

…meaning I need in to concatenate names for every column (not exactly the name of the column but a different text for every column) that is not 0.

Best Answer

Something like (untested):

select
  id,
  rtrim(
    case when c1 != 0 then 'column1,' end
 || case when c2 != 0 then 'column2,' end
 || case when c3 != 0 then 'column3,' end
 || case when c4 != 0 then 'column4,' end
 || case when c5 != 0 then 'column5' end, ',') as descr
from tab1;