SQL - 子表记录父对象的透视 - Oracle

时间:2017-12-11 01:56:18

标签: sql oracle11g string-aggregation

我有父母& Oracle下面的子表如下所示。

必须显示以逗号分隔的子记录。

T_OPT_PARENT

OPT | OPT_DESC| STATUS 
XY  | XY_DESC | A 
YZ  | YZ_DESC | A 
ZZ  | ZZ_DESC | A 

T_OPT_CHILD

OPT | CODE
XY  | ONE_CODE
XY  | TWO_CODE
XY  | THREE_CODE
ZZ  | ONE_CODE
ZZ  | TWO_CODE

预期输出

OPT | OPT_DESC| CODE                         | STATUS 
XY  | XY_DESC | ONE_CODE,TWO_CODE,THREE_CODE | A
YZ  | YZ_DESC |                              | A 
ZZ  | ZZ_DESC | ONE_CODE, TWO_CODE           | A 

有人可以帮我构建一个SQL查询来获得预期的结果。

1 个答案:

答案 0 :(得分:0)

试试这个答案:

SELECT A.OPT,A.OPT_DESC,D.List AS CODE,A.STATUS FROM T_OPT_PARENT A
LEFT JOIN(
select OPT,
  listagg(CODE, ',') 
    within group (order by OPT) as list 
from T_OPT_CHILD
group by OPT)D ON A.OPT=D.OPT
ORDER BY A.OPT

检查SQL小提琴中的答案: SQL Fiddle