查询将多个数据存储在一行中的数组中

时间:2017-01-04 09:38:58

标签: sql oracle

假设我有一个# redis is a connection to my redis server all_keys = redis.keys # list of all keys in redis for i in all_keys do # iterate through all keys in redis if (redis.hgetall i)["success"] == true # if that key has success = true attrib completed_keys.append(i) # append that key to a new list end end 表,其中包含一群用户Usersid以及name表,其中包含所有可能的组{ {1}}和Groups

一个用户可以在多个

id

如何选择所有用户并将他们的论坛存储在1列内?

结果将是

name

4 个答案:

答案 0 :(得分:2)

您可以在此处使用listagg

select id, name, listagg("group", ',') within group (order by "group") "groups"
from Groups
group by id, name;

如果您的用户表格中包含列' id'和' name'和群组表格中有列' id' (该用户的ID)和' name' (该组的名字),然后使用:

select u.id, u.name, listagg(g.name, ',') within group (order by g.name)
from users u
inner join groups g
on u.id = g.id
group by u.id, u.name;

答案 1 :(得分:1)

您可能需要使用LISTAGG进行简单聚合:

with test(id, name, groups) as (
  select 1, 'Alice',  'User' from dual union all
  select 1, 'Alice',  'Technician' from dual union all
  select 2, 'Bob',  'Admin' from dual)
select id, name, listagg(groups, ', ') within group (order by groups)
from test
group by id, name

这给出了:

1    Alice    Technician, User
2    Bob      Admin

假设您要加入两个表:

with users(id, name) as (
  select 1, 'Alice' from dual union all
  select 2, 'Bob'   from dual
),
groups (id, groupId) as (
  select 1, 'User' from dual union all
  select 1, 'Technician' from dual union all
  select 2, 'Admin' from dual
)    
select u.id, name, listagg(groupId, ', ') within group (order by groupId)
from users u
      inner join groups g
        on (g.id = u.id)
group by u.id, name;

给出了相同的结果:

1    Alice    Technician, User
2    Bob      Admin

答案 2 :(得分:0)

试试这个

 SELECT id,name,group_concat(groups) as groups from users group by name

答案 3 :(得分:0)

Listagg->它还允许我们根据您的group by子句对连接列表中的元素进行排序。请在下面找到查询供您参考。

SELECT id,name,LISTAGG(dept, ',') WITHIN GROUP (ORDER BY dept) AS department
from emp
GROUP BY id,name;

如果您需要进一步说明,请发表评论。