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)?
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.