簡體   English   中英

將多個列值合並為一個並在多行中打印一個字符串-Oracle SQL

[英]Combine multiple column values to one and print the one string in multiple rows - oracle SQL

我不知道從哪里開始查詢。 Stuff()函數無助於獲得我想要的結果。 任何幫助表示贊賞。

我的桌子:

+-----+-----------+--------+
| 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   |
+-----+-----------+--------+---------------+

使用LISTAGG和子查詢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連結

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

您可以使用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   |
+-----+-----------+--------+---------------+

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM