jondinham
jondinham

Reputation: 8511

Oracle SQL 'select' with 1 column having combined values

Table t1:

pk_id | col1 | col2 | col3
===========================
1     | val1 | val2 | val3

Table t2: (fk_id is foreign key references to pk_id)

fk_id | col4
=============
1     | val4A
1     | val4B
1     | val4C

My SQL query is:

select pk_id,col1,col2,col3,col4
from t1 left join t2 on t1.pk_id=t2.fk_id;

The result is:

pk_id | col1 | col2 | col3 | col4
===================================
1     | val1 | val2 | val3 | val4A
1     | val1 | val2 | val3 | val4B
1     | val1 | val2 | val3 | val4C

But I actually want this result:

pk_id | col1 | col2 | col3 | col4
===============================================
1     | val1 | val2 | val3 | val4A;val4B;val4C

How to change the 'select' query to achieve this result with col4 value is the combined values of val4A, val4B, val4C (separated by semicolons)?

Upvotes: 1

Views: 142

Answers (1)

Yigitalp Ertem
Yigitalp Ertem

Reputation: 2039

You can use LISTAGG for that.

select pk_id,col1,col2,col3,
                    LISTAGG (t2.col4, ';') WITHIN GROUP (ORDER BY t2.col4) AS col4
from t1 left join t2 on t1.pk_id=t2.fk_id
group by pk_id, col1, col2, col3;

Upvotes: 2

Related Questions