Sorry for the long title but it's a little bit difficult to explain.
We have a table
| N rows | Atrib1 | Atrib2 | Atrib3 | Atrib4 | Final row | --------------------------------------------------------------- | N1 | R | X | One | A1 | True | | N1 | D | Y | | | False | | N1 | K | Z | | | False | | N1 | N | A | | | True | ---------------------------------------------------------------
We must aggregate all the Atribs column into a single line with ';' separator in the order marked in the table, because we are trying to do an export to a CSV file.
We have no problem with the aggregation but there is a special condition that we must follow. If a row or more rows, from sequence (R, D, K, N) for Atrib1, doesn't exist we must even include a set of ';' for each Atrib(1..4).
The query that we have already works fine if all the rows are filled but not when someone is missing.
select N rows, LISTAGG(Atrib1 ||';'|| coalesce(Atrib2,'') ||';'|| coalesce(Atrib3,'') ||';'|| coalesce(Atrib4,''), ';') WITHIN GROUP (ORDER BY Code_crit_0) "Employees", Final row
from TABLE
group by N rows
order by decode(Code_crit_0, 'R',1,'D',2,'K',3,'N',4, 5) asc;
Any idea of how to accomplished this special condition without any SQL procedure.
Thanks in advance.
Best Answer
Suppose you have the following table (called TEST). Some of the the "nrows" - N2, N3, N4, N5 - do not have a complete set of (R,D,K,N) values.
As a first step, you could write a query that generates the missing nrows/A1 combinations (NA1), and LEFT JOIN it to the original (O) table.
Then, use LISTAGG and DECODE (if CASE ... , as used in the example below, is too "bulky") and replace the NULLs with ;
Result
Tested with Oracle 12c, and Oracle 11g. Dbfiddle here.