我有一份学生和家长的名单,并希望使用学生证将他们分组。拥有共同学生证的父母可以被视为一个家庭,而拥有共同父母证的学生也可以被视为一个家庭。这是一个示例表:
p_id | parent_name | s_id | student_name |
------------------------------------------|
1 | John Doe | 100 | Mike Doe |
3 | Jane Doe | 100 | Mike Doe |
3 | Jane Doe | 105 | Lisa Doe |
5 | Will Willy | 108 | William Son |
我想最终得到类似的东西:
parents | students |
-------------------|------------------------|
John Doe, Jane Doe | Mike Doe, Lisa Doe |
Will Willy | William Son |
为了实现这一点,我目前正在使用:
SELECT array_agg(parents) AS parents FROM (
SELECT array_agg(p_id) AS par_ids, array_agg(parent_name) AS parents, student_name, s_id
FROM (
/* sub query */
)b
GROUP BY s_id, student_name
ORDER BY parents ASC
)c
GROUP BY unnest(par_ids)
ORDER BY parents ASC
但我得到一个错误:ERROR: cannot accumulate arrays of different dimensionality
。SQL state: 2202E
我怎样才能达到预期的结果?上述语句的内部查询返回:
| par_ids | parents | student_name | s_id |
--------------------------------|------------------------|
| {1,3} | {John Doe, Jane Doe}| Mike Doe | 100 |
| {3} | {Jane Doe} | Lisa Doe | 105 |
| {5} | {Will Willy} | William Son | 108 |
现在将这些学生归为父母是我的难题。