[英]How do I create a new column that holds all the primary key values of all rows that have the same value?
I read through multiple Questions here, but did not find the answer suiting my problem.我在这里阅读了多个问题,但没有找到适合我的问题的答案。
My table holds the following columns:我的表包含以下列:
id | name | fav_team
1 John Seahawks
2 Patrick Bengals
3 Tom Seahawks
4 Kate Seahawks
So I already figured out how to ask for all ids whose fav_team is 'Seahawks' but how do I manage to create a new column that for id 1 holds all the ids of that rows that have 'Seahawks' as fav_team as well, so that my output will look like this:所以我已经想出了如何询问所有 fav_team 为“Seahawks”的 id,但是我如何设法创建一个新列,其中 id 1 包含所有具有“Seahawks”作为 fav_team 的行的 id,这样我的 output 将如下所示:
id | same_team
1 3, 4
3 1, 4
4 1, 3
use group_concat()使用 group_concat()
select group_concat(id) from table t1
where exists ( select 1 from table t2 where t1.fav_team=t2.fav_team
) and
You can us a correlated subquery:您可以使用相关子查询:
select t.*,
(select group_concat(id order by id)
from t t2
where t2.fav_team = t.fav_team and t2.id <> t.id
) as others_with_same_favorite
from t;
You can also do this with window functions, but it requires diving into JSON and doing a lot of string manipulation:您也可以使用 window 函数执行此操作,但需要深入了解 JSON 并进行大量字符串操作:
select id,
trim(',' from
replace(regexp_replace(json_unquote(json_arrayagg(id) over (partition by fav_team)), '\\[|\\]|, ', ','),
concat(',', id, ','), ','
)
)
from t
order by id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.