将用户id列与PostgreSQL 13上的字符串_agg一起分组
这是我的将用户id列与PostgreSQL 13上的字符串_agg一起分组,postgresql,Postgresql,这是我的电子邮件表格 create table emails ( id bigint not null primary key generated by default as identity, name text not null ); 和联系人表: create table contacts ( id bigint not null primary key generated by default as identity, email_id bigi
电子邮件
表格
create table emails (
id bigint not null primary key generated by default as identity,
name text not null
);
和联系人
表:
create table contacts (
id bigint not null primary key generated by default as identity,
email_id bigint not null,
user_id bigint not null,
full_name text not null,
ordering int not null
);
如您所见,我在这里有user\u id
字段。我的结果上可能有多个相同的用户ID,因此我想使用逗号,
在表中插入一些数据:
insert into emails (name)
values
('dennis1'),
('dennis2');
insert into contacts (id, email_id, user_id, full_name, ordering)
values
(5, 1, 1, 'dennis1', 9),
(6, 2, 1, 'dennis1', 5),
(7, 2, 1, 'dennis1', 1),
(8, 1, 3, 'john', 2),
(9, 2, 4, 'dennis7', 1),
(10, 2, 4, 'dennis7', 1);
我的问题是:
select em.name,
c.user_ids
from emails em
join (
select email_id, string_agg(user_id::text, ',' order by ordering desc) as user_ids
from contacts
group by email_id
) c on c.email_id = em.id
order by em.name;
实际结果
预期结果
在我的真实数据中,我得到了50次相同的用户id。相反,它应该只出现一次。在上面的示例中,您看到用户1
和4
为dennis2
用户出现了两次
我怎样才能使它们独一无二
演示:
备注:我试图将用户id
添加到分组依据中,但这次我得到了重复的行…
加入表格
在
电子邮件和用户id
上是不同的,因此对于每个电子邮件记录,没有相等的用户
聚合
name user_ids
dennis1 1,3
dennis2 1,1,4,4
name user_ids
dennis1 1,3
dennis2 1,4
SELECT
name,
string_agg(user_id::text, ',' order by ordering desc)
FROM (
SELECT DISTINCT ON (em.id, c.user_id)
*
FROM emails em
JOIN contacts c ON c.email_id = em.id
) s
GROUP BY name