Oracle 分组依据和数据透视

Oracle group by and pivot

我在 Oracle 11g 数据库中有一个 table,如下所示:

ownerid | propertyid | name
--------------------------------------
1       | 1000001    | SMITH MARY
2       | 1000001    | SMITH JOHN
3       | 1000002    | HUGHES JANE
4       | 1000003    | CHEN ALICE
5       | 1000003    | MCCOY ELLIS

我正在尝试将 table 分组到 propertyid 并将行转为列,这样它看起来像这样:

propertyid | owner1         | owner2
---------------------------------------------
10001      | SMITH MARY     | SMITH JOHN
10002      | HUGHES JANE    | <null>
10003      | CHEN ALICE     | MCCOY ELLIS

每个 属性 可以有 1 到 3 个所有者,但我只对前两个感兴趣,因为它们在 ownerid 上订购时出现。

我最好的解决方案是创建两个子查询:一个 "first" 所有者和另一个 "second" 所有者。我使用 nth_value 函数如下:

-- first owners
select 
  propertyid,
  nth_value(name, 1) over (partition by propertyid order by ownerid) as owner_1
from owners

但是,如果所有者总数大于 1,这会给我重复(尽管正确)的属性和所有者对。总的来说,我觉得必须有更好的方法来做到这一点。有人有什么想法吗?

with
     inputs ( ownerid, propertyid, name ) as (
       select 1, 1000001, 'SMITH MARY'  from dual union all
       select 2, 1000001, 'SMITH JOHN'  from dual union all
       select 3, 1000002, 'HUGHES JANE' from dual union all
       select 4, 1000003, 'CHEN ALICE'  from dual union all
       select 5, 1000003, 'MCCOY ELLIS' from dual
     ),
     prep ( propertyid, name, rn ) as (
       select propertyid, name,
              row_number() over (partition by propertyid order by ownerid)
       from   inputs
     )
select * 
from prep
pivot (max(name) for rn in (1 as owner1, 2 as owner2))
order by propertyid
;


PROPERTYID OWNER1      OWNER2
---------- ----------- -----------
   1000001 SMITH MARY  SMITH JOHN
   1000002 HUGHES JANE
   1000003 CHEN ALICE  MCCOY ELLIS

3 rows selected.