让我说我有一堆team_id
。
team_id|username
-------|--------
1| u1
1| u2
2| u3
2| u1
2| u2
3| u1
3| u2
3| u4
因此,对于每个team_id
,我想查找是否有任何两个用户始终具有相同的team_id.
因此,在上面的示例中,查询应返回u1
和u2
因为他们总是在同一个团队中。有点难以解释......有什么想法吗?
答案 0 :(得分:1)
构建数据:
t=# create table so17(team_id int,username text);
CREATE TABLE
t=# copy so17 from stdin delimiter '|';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1| u1
1| u2
2| u3
2| u1
2| u2
3| u1
3| u2
3| u4>> >> >> >> >> >> >>
>> \.
COPY 8
选择
t=# with e as (with i as (select *,array_agg(team_id) over (partition by username) from so17)
select distinct username,count(1) over (partition by array_agg) from i)
select username from e where count > 1;
username
----------
u2
u1
(2 rows)