Объединить несколько значений столбцов в одно и вывести одну строку в несколько строк - Oracle SQL - PullRequest
0 голосов
/ 07 февраля 2019

Я не знаю, с чего начать этот запрос.Функция 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   |
+-----+-----------+--------+---------------+

Ответы [ 2 ]

0 голосов
/ 07 февраля 2019

Вы можете использовать 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   |
+-----+-----------+--------+---------------+

Демо

0 голосов
/ 07 февраля 2019

использование 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
...