postgresql 聚合来自两个不同表中两列的字符串在Postgres中JOINed

jecbmhm3  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(158)

下面是我的表在postgres数据库中的存在方式-
学生
| 身份证|姓名|
| - -----|- -----|
| 1|罗杰|
| 2|罗曼|
学校
| 身份证|姓名|地址_ID|学生ID|
| - -----|- -----|- -----|- -----|
| 1|学校1| 1| 1|
| 2|学校2| 2| 1|
| 3|学校3| 3| 2|
学院
| 身份证|姓名|地址_ID|学生ID|
| - -----|- -----|- -----|- -----|
| 1|学院1| 1| 1|
| 2|学院2| 3| 2|
联系方式
| 身份证|姓名|
| - -----|- -----|
| 1|布鲁克林|
| 2|曼哈顿|
| 3|特洛伊|
我想一个SQL查询,以获得学生ID,学生姓名和地方,他们已经在学校和大学生活的过程中。
| ID|学生姓名|参观景点|
| - -----|- -----|- -----|
| 1|罗杰|布鲁克林曼哈顿|
| 2|罗曼|特洛伊|
我试过这样的方法,但不管用-

SELECT 
   s.Id AS 'ID', 
   s.Name AS 'Student Name',
   STRING_AGG(a.Name, ', ')AS 'Visited Places'
FROM Student s
   LEFT JOIN School sc ON sc.Student_Id = s.Id
   LEFT JOIN Address a ON a.Id = sc.Address_Id
   LEFT JOIN College c ON c.Student_Id = s.Id
   LEFT JOIN Address a ON a.Id = c.Address_Id;
1sbrub3j

1sbrub3j1#

有几种方法可以做到这一点。下面的查询首先确定所有唯一的学生和地址对。查询的主要部分使用这些来连接学生和地址。

WITH
  visited_addresses AS (
    SELECT student_id, address_id
      FROM School
    UNION
    SELECT student_id, address_id
      FROM College
  )
SELECT s.id AS "ID",
       s.name AS "Student Name",
       string_agg(a.name, ', ' ORDER BY a.name) AS "Visited Places"
  FROM Student s
  LEFT JOIN visited_addresses v
    ON s.id = v.student_id
  LEFT JOIN Address a
    ON v.address_id = a.id
 GROUP BY s.id, s.name
 ORDER BY s.id;

下一个查询返回相同的结果,但使用横向连接来获取每个学生的访问地址:

SELECT s.id AS "ID",
       s.name AS "Student Name",
       string_agg(a.name, ', ' ORDER BY a.name)
  FROM Student s
  LEFT JOIN LATERAL (SELECT sc.address_id
                        FROM School sc
                       WHERE sc.student_id = s.id
                      UNION
                      SELECT c.address_id
                        FROM College c
                       WHERE c.student_id = s.id
                     ) v
    ON TRUE
  LEFT JOIN Address a
    ON v.address_id = a.id
 GROUP BY s.id, s.name
 ORDER BY s.id;

相关问题