在多行合并多个列中的值,以一个并打印一个字符串 - 的Oracle SQL

问题描述 投票:0回答:2

我不知道从哪里开始与该查询。东西()函数没有帮助,让我想要的结果。任何帮助表示赞赏。

我的表:

+-----+-----------+--------+
| uid |   uname   |  host  |
+-----+-----------+--------+
|   1 | testuser  | host 1 |
|   2 | testuser  | host 2 |
|   3 | testuser2 | host 3 |
|   4 | testuser2 | host 4 |
+-----+-----------+--------+

预期输出:

+-----+-----------+--------+---------------+
| uid |   uname   |  host  | combined host |
+-----+-----------+--------+---------------+
|   1 | testuser  | host 1 | host1,host2   |
|   2 | testuser  | host 2 | host1,host2   |
|   3 | testuser2 | host 3 | host3,host4   |
|   4 | testuser2 | host 4 | host3,host4   |
+-----+-----------+--------+---------------+
sql oracle oracle11g oracle11gr2
2个回答
1
投票

使用LISTAGG和子查询加盟

    with cte as
(
select 1  uid1 ,'testuser' as uname,'host 1' as host from DUAL union all
select 2  uid1 ,'testuser' as uname,'host 2' as host from DUAL union all
select 3  uid1 ,'testuser2' as uname,'host 3' as host from DUAL union all
select 4  uid1 ,'testuser2' as uname,'host 4' as host from DUAL

)
  select cte.uname,cte.host,val from cte join (
 select uname,LISTAGG(host,',') within group (order by host) as val
 from cte group by uname) t on cte.uname=t.uname

dmeo link

UNAME       HOST          VAL
testuser    host 1  host 1,host 2
testuser    host 2  host 1,host 2
testuser2   host 3  host 3,host 4
testuser2   host 4  host 3,host 4

0
投票

您可以如下使用listagg()窗口解析函数:

with tab("uid",uname,host ) as
(
 select 1,'testuser' ,'host 1' from dual union all
 select 2,'testuser' ,'host 2' from dual union all
 select 3,'testuser2','host 3' from dual union all
 select 4,'testuser2','host 4' from dual
)
select  t2.*, t1."combined host"
  from
(select uname, listagg(host,',') within group (order by uname)
     as "combined host"          
   from tab
  group by uname ) t1
  inner join ( select * from tab ) t2 on t1.uname = t2.uname;

+-----+-----------+--------+---------------+
| uid |   UNAME   |  HOST  | combined host |
+-----+-----------+--------+---------------+
|   1 | testuser  | host 1 | host1,host2   |
|   2 | testuser  | host 2 | host1,host2   |
|   3 | testuser2 | host 3 | host3,host4   |
|   4 | testuser2 | host 4 | host3,host4   |
+-----+-----------+--------+---------------+

Demo

© www.soinside.com 2019 - 2024. All rights reserved.