在 Oracle 中用逗号分隔值连接 3 个或更多表

Join 3 or more tables with Comma separated values in Oracle

我有 3 个表(一个 parent 和 2 个 child)如下

StudentID | Name |  Age
    1     |  AA  |  23
    2     |  BB  |  25
    3     |  CC  |  27
BookID    | SID | BookName |  BookPrice
    1     |  1  |  ABC     |    20
    2     |  1  |  XYZ     |    15
    3     |  3  |  LMN     |    34
    4     |  3  |  DDD     |    90
 PenID    | SID | PenBrandName |  PenPrice
    1     |  2  |      LML     |    20
    2     |  1  |      PARKER  |    15
    3     |  2  |      CELLO   |    34
    4     |  3  |      LML     |    90

我需要加入表格并获得如下所示的输出

StudentID | Name |  Age | BookNames  | TotalBookPrice  | PenBrands  | TotalPenPrice
    1     |  AA  |  23  |  ABC, XYZ  |       35        |   PARKER   |       15 
    2     |  BB  |  25  |    null    |       00        | LML, CELLO |       54
    3     |  CC  |  27  |  LMN, DDD  |       124       |   LML      |       90

这是我试过的代码:

Select s.studentID as "StudentID", s.name as "Name", s.age as "AGE", 
LISTAGG(b.bookName, ',') within group (order by b.bookID) as "BookNames",
SUM(b.bookPrice) as "TotalBookPrice",
LISTAGG(p.penBrandName, ',') within group (order by p.penID) as "PenBrands",
SUM(p.penPrice) as "TotalPenPrice"
FROM Student s
LEFT JOIN BOOK b ON b.SID = s.StudentID
LEFT JOIN PEN p ON p.SID = s.StudentID
GROUP BY s.studentID, s.name, s.age

我得到的结果有 Book 和 Pen 的多个值(叉积结果有多个值)

StudentID | Name |  Age |      BookNames    | TotalBookPrice  |     PenBrands     | TotalPenPrice
    1     |  AA  |  23  |  ABC,ABC,XYZ,XYZ  |       35        |   PARKER,PARKER   |       15 

请告诉我如何解决这个问题。

不是连接表并进行聚合,而是必须先聚合然后连接表 -

Select s.studentID as "StudentID", s.name as "Name", s.age as "AGE", 
"BookNames",
"TotalBookPrice",
"PenBrands",
"TotalPenPrice"
FROM Student s
LEFT JOIN (SELECT SID, LISTAGG(b.bookName, ',') within group (order by b.bookID) as "BookNames", 
                  SUM(b.bookPrice) as "TotalBookPrice"
             FROM BOOK
            GROUP BY SID) b ON b.SID = s.StudentID
LEFT JOIN (SELECT SID, LISTAGG(p.penBrandName, ',') within group (order by p.penID) as "PenBrands", 
                  SUM(p.penPrice) as "TotalPenPrice"
             FROM PEN
            GROUP BY SID) p ON p.SID = s.StudentID;