2017-10-10 58 views
0

例如: - 我有3個表。如何在select查詢oracle中的列中組合多個行數據?

學生

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 

書籍有多個地址:可以有muliple書用戶

 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的結果。

AddressList中,可就是這樣,你可以創建列表,你想,但它應該有所有這些數據。

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

相同的書目

在此先感謝。

+1

集團由'student_id'和使用'listagg'和字符串連接''||獲得地址和書籍的字符串。 –

+1

如果它只是一個報告查詢,您可以創建它在此之後,或把它放在一個視圖,你可以用'LISTAGG()'內置函數選擇地址,水木清華這樣的'選擇s.student_id,S。名,s.rollno,s.class ,LISTAGG(a.country || '' || a.district || '' || a.street)組中(以a.country順序)AddressList中 ,LISTAGG( b.book_id ||''|| b.book)in group(order by a.book_id)as booklist from student's,address a,books b where s.student_id = a.student_id and s.student_id = b .student_id;也可以添加group by。 – g00dy

+1

@ g00dy這會給出錯誤ORA-00937:不是單組功能 –

回答

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); 
+0

單選查詢不能做到嗎? –

+0

@Himanshusharma完成一個查詢。如果你的意思是「我可以加入表格然後使用'LISTAGG'」嗎?不是如果你不想在你的JSON中重複。 – MT0

+0

這對我和所有尋求解決方案的人都有幫助。 –