2016-05-28 25 views
1

我想列出所有管理者從這個模式管理的出租物業:集團通過結果到一個列表

Create Table Rental_Property(property_number int Primary Key, managerId 
int, Foreign Key(managerId) References manage(managerId)); 

這裏我的方法:

Create Or Replace Procedure supervisor_properties 
As 
     list_of_properties varchar (300) := ' '; 
Begin 
     Select 'Manager' || ': ' || managerId || ' ' || property_number 
     Into list_of_properties 
     From Rental_Property 
     Group By managerId; 
End; 

我有麻煩的部分是上面的程序group by將所有具有相同managerId的元組分組在一起。現在怎麼辦我打印出來的結果是這樣的:

Manager m1: Rental_Prop1, Rental_Prop2, Rental_Prop3 
Manager m2: Rental_Prop9, Rental_Prop6, Rental_Prop4 

回答

1

您可以使用list_agg()

Select (managerId || ' ' || 
      list_agg(property_number, ' ') within group (order by property_number) 
      ) 
    Into list_of_properties 
    From Rental_Property 
    Group By managerId; 

唯一的問題是,into是把值到一個變量。 。 。如果group by有多個管理器,則會產生錯誤。

開始與此查詢:

Select managerId, 
     list_agg(property_number, ' ') within group (order by property_number) as properties 
From Rental_Property 
Group By managerId; 

編輯:

我明白了。如果你要打印的價值觀:

Create Or Replace Procedure supervisor_properties 
As 
Begin 
    for x in (Select managerId, 
        list_agg(property_number, ' ') within group (order by property_number) as properties 
       From Rental_Property 
       Group By managerId 
      ) 
    loop 
     dbms_output.put_line(x.managerId || ' ' || x.properties); 
    end loop; 
End; 
+0

你好,你能不能請你的意思是什麼解釋「唯一的問題是,到是放值到一個變量,這將產生,如果錯誤。這個小組由多個經理組成。?「因爲'group by'將在每個組中只有一個managerId。 – DF768

+0

@ DF768。 。 。這就是'進入'所做的。從第二個查詢開始。 –