Oracle使用逗号分隔的值选择四个表的值

时间:2019-01-23 12:33:04

标签: sql oracle

我有四个表,名称分别为APP_PROFILEORIGTERMTERM_FAIL。我想选择它们的值,并用逗号分隔它们。顺便说一下,我找到了listagg函数,但据我所知listagg函数不能工作多个列。

我的表格如下;

Table: APP_PROFILE
-----------------------
ID      NAME
--   ------------
1     profile_anil
2     profile_anil2

Table: ORIG
-----------------------
PROFILE_NAME      ORIG_ID
------------     ---------
profile_anil        3
profile_anil        4
profile_anil2       5
profile_anil2       6

Table: TERM
-----------------------
PROFILE_NAME      TERM_ID
------------     ---------
profile_anil        7
profile_anil        8
profile_anil2       9
profile_anil2       10

Table: TERM_FAIL
-----------------------
PROFILE_NAME      TERM_FAIL_ID
------------     -------------
profile_anil           11
profile_anil           12
profile_anil2          13
profile_anil2          14


Table: Result
-----------------------
PROFILE_NAME    ORIG_ID    TERM_ID    TERM_FAIL_ID
------------   ---------  ---------   -------------
profile_anil     3,4        7,8          11,12
profile_anil2    5,6        9,10         13,14

2 个答案:

答案 0 :(得分:1)

您可以使用子查询:

select ap.*,
       (select listagg(orig_id, ',') within group (order by orig_id)
        from orig o
        where o.profile_name = ap.profile_name
       ) as origs,
       (select listagg(term_id, ',') within group (order by term_id)
        from term t
        where t.profile_name = ap.profile_name
       ) as terms,
       (select listagg(term_fail_id, ',') within group (order by term_fail_id)
        from term_fail tf
        where tf.profile_name = ap.profile_name
       ) as term_fails
from app_profile ap;

答案 1 :(得分:0)

SELECT A.PROFILE_NAME, 
       LISTAGG(ORIG_ID,',') ORIG_ID, 
       LISTAGG(TERM_ID,',') TERM_ID, 
       LISTAGG(TERM_FAIL_ID,',') TERM_FAIL_ID
  FROM APP_PROFILE A, 
       ORIG B,
       TERM C,
       TERM_FAIL D
 WHERE A.PROFILE_NAME = B.PROFILE_NAME
   AND B.PROFILE_NAME = C.PROFILE_NAME
   AND C.PROFILE_NAME = D.PROFILE_NAME
 GROUP BY A.PROFILE_NAME