在 PostgresQL 表中,如何创建列 1 中所有值的列,这些值曾经出现在第 2 列中,以出现该行的列 1 值?



我有一个Postgres表,格式如下:

BeckyMillie利比
人的女儿 人的母亲
Becky Sally 不在列表中
Sally Libby
SallyBecky
米莉N/A莎莉

最简单的方法是使用window functions:

SELECT 
*,string_agg(persons_daughter,',') OVER (PARTITION BY person)
FROM t;

上面的查询正是您所期望的,即使用person作为分区在列persons_daughter上应用聚合函数string_agg

演示:db<>fiddle

SELECT 
mother.person, 
mother.persons_daughter, 
mother.persons_mother, 
STRING_AGG(daughter.person, ',') as all_of_persons_daughters
FROM table AS mother
INNER JOIN table AS daughter
ON mother.person = daughter.persons_mother
GROUP BY mother.person, mother.persons_daughter, mother.persons_mother

最新更新