如何在select查询oracle中的列中组合多行数据?

时间:2017-10-10 07:55:41

标签: oracle join

例如: - 我有3张桌子。

学生

student_id | name | rollNo | class 
         1 |  a1  | 12     | 5
         2 |  b1  | 11     | 5

地址:用户可以有多个地址

street  | district| country |student_id
  gali1 | nanit   | india | 1
  gali2 | nanital | india | 1

图书:可以为用户提供多种书籍

       book   | book_id |student_id
      history | 111      | 1
      Science | 112    | 1

这是一个例子。我希望数据在输出中像这样。 如果我选择student_id 1.那么这将是结果

student_id | name | rollNo | class | addresslist   | booklist
          1 |  a1  | 12     |  5    | some sort of |  some sort of
                                    |  list which  |  list which
                                    |  contain both|  contain both
                                    |  the address |  the book detail
                                    |  of user     |  of user

我正在使用12.1,它现在不支持json,它在12.2。

地址列表可以像这样你可以根据需要创建列表,但它应该包含所有这些数据。

[{street:"gali1","distict":"nanital","country":"india","student_id":1},{"street":"gali2","distict":"nanital","country":"india","student_id":1}]

相同的书目

提前致谢。

1 个答案:

答案 0 :(得分:1)

类似的东西:

WITH json_addresses ( address, student_id ) AS (
  SELECT '[' ||
         LISTAGG(
           '{"street":"' || street || '",'
             || '"district":" || district || '",'
             || '"country":" || country|| '"}',
           ','
         ) WITHIN GROUP ( ORDER BY country, district, street )
         || ']',
         student_id
  FROM   address
  GROUP BY student_id
),
json_books ( book, student_id ) AS (
  SELECT '[' ||
         LISTAGG(
           '{"book_id":"' || book_id || '",'
             || '"book":" || book || '"}',
           ','
         ) WITHIN GROUP ( ORDER BY book, book_id )
         || ']',
         student_id
  FROM   book
  GROUP BY student_id
)
SELECT s.*, a.address, b.book
FROM   student s
       INNER JOIN json_addresses a
       ON ( s.student_id = a.student_id )
       INNER JOIN json_books b
       ON ( s.student_id = b.student_id );