按结果分组到列表

时间:2016-05-28 16:55:42

标签: sql oracle11g

我正在尝试列出经理从此架构管理的所有出租物业:

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 个答案:

答案 0 :(得分: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;