我正在寻找一个可以从多个表中获取多个字段并将它们合并到一个字段中的查询。防爆。我的查询看起来像:
select to_char(a.comments), to_char(b.comments), to_char(c.comments)
from crm.custprob a
left join crm.custcall b on b.servno = a.servno
left join crm.custlog c on c.servno = b.servno
where a.servno = 1716942
并生成输出:
a.comments b.comments c.comments 1 Regular 3 Primary 5 Log 1 Regular 3 Primary 4 Log 1 Regular 2 Other 5 Log 1 Regular 2 Other 4 Log
我想要的是一个查询,它会在一行中生成输出,并在一个字段中(我不关心数字的顺序)所以它看起来像:
Comments 1 Regular 2 Other 3 Primary 4 Log 5 Log
答案 0 :(得分:1)
首先获取所有评论的列表。您将UNION
用于此,而不是加入。然后使用LISTAGG
聚合行并连接注释:
select listagg(comments, ' ') within group (order by comments) as comments
from
(
select to_char(comments) as comments from crm.custprob where servno = 1716942
union
select to_char(comments) as comments from crm.custcall where servno = 1716942
union
select to_char(comments) as comments from crm.custlog where servno = 1716942
);
(如果没有重复项,您可以使用UNION ALL
代替UNION
。)
(根据以下评论进行了更新,其中显示comments
属于NCLOB
类型。)
答案 1 :(得分:0)
这是在加入之前对各个表执行listagg的替代方法:
WITH t1 AS (SELECT 1 ID, '1 regular' comments FROM dual UNION ALL
SELECT 2 ID, '1 abnormal' comments FROM dual),
t2 AS (SELECT 1 ID, '2 other' comments FROM dual UNION ALL
SELECT 1 ID, '3 primary' comments FROM dual UNION ALL
SELECT 2 ID, '2 something else' comments FROM dual UNION ALL
SELECT 2 ID, '3 secondary' comments FROM dual),
t3 AS (SELECT 1 ID, '4 log' comments FROM dual UNION ALL
SELECT 1 ID, '5 log' comments FROM dual UNION ALL
SELECT 2 ID, '4 log' comments FROM dual UNION ALL
SELECT 2 ID, '5 log' comments FROM dual)
SELECT t1.id,
t1.comments||' '||t_2.comments||' '||t_3.comments comments
FROM t1
LEFT OUTER JOIN (SELECT ID, listagg(comments, ' ') WITHIN GROUP (ORDER BY comments) comments
FROM t2
GROUP BY ID) t_2 ON t1.id = t_2.id
LEFT OUTER JOIN (SELECT ID, listagg(comments, ' ') WITHIN GROUP (ORDER BY comments) comments
FROM t3
GROUP BY ID) t_3 ON t_2.id = t_3.id;
ID COMMENTS
---------- --------------------------------------------------------------------------------
1 1 regular 2 other 3 primary 4 log 5 log
2 1 abnormal 2 something else 3 secondary 4 log 5 log
答案 2 :(得分:0)
这有用吗?
select listagg(comments, ' ') within group (order by ordering) as comments
from (select comments from crm.custprob, 1 as ordering where servno = 1716942
union all
select comments from crm.custcall, 2 where servno = 1716942
union all
select comments from crm.custlog, 3 where servno = 1716942
) x;