简体   繁体   English

具有1个列的Oracle SQL'select'具有合并值

[英]Oracle SQL 'select' with 1 column having combined values

Table t1: 表t1:

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

Table t2: (fk_id is foreign key references to pk_id) 表t2:(fk_id是对pk_id的外键引用)

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

My SQL query is: 我的SQL查询是:

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)? 如何更改“选择”查询以使用col4值实现此结果,即val4A,val4B,val4C的组合值(用分号分隔)?

You can use LISTAGG for that. 您可以使用LISTAGG

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM