编写Oracle Left Join以生成非规范化分隔列

时间:2018-05-08 15:55:12

标签: sql oracle denormalization

假设:

TABLE_X

id        
-------
 1       
 2 
 3       
 4        

Table_Y

id_foreign   | content
-------------+-------------------
1            | A
1            | B
1            | C
1            | D
4            | E  
6            | F  
6            | G  

常规left join Table_Y ON Table_X.id = Table_Y.id_foreign会产生标准化输出,但这不是我想要的结果。是否可以轻松生成以下内容而无需在SQL之外进行后处理?内容字段是非规范化的,并用分隔符分隔:

id           | content
-------------+-------------------
1            | A,B,C,D
2            | 
3            | 
4            | E

1 个答案:

答案 0 :(得分:3)

您正在寻找listagg()

select x.id, listagg(y.content, ',') within group (order by y.content)
from table_x x left join
     table_y y 
     on x.id = y.id_foreign
group by x.id;