基于Oracle SQL优先级的pivot

时间:2017-02-01 17:16:00

标签: sql oracle pivot

我想显示一个customer_id列表,其中前五个地址显示为其旁边的列,基于claim_count的数量。是否有可能使用PIVOT?

CREATE TABLE pivot_test (
customer_id   NUMBER,
claims_count NUMBER,
address  VARCHAR2(5)
);

INSERT INTO pivot_test VALUES (1,23,'A');
INSERT INTO pivot_test VALUES (1,2,'B');
INSERT INTO pivot_test VALUES (1,43,'C');
INSERT INTO pivot_test VALUES (1,0,'D');
INSERT INTO pivot_test VALUES (1,34,'E');
INSERT INTO pivot_test VALUES (1,23,'F');
INSERT INTO pivot_test VALUES (2,6,'A');
INSERT INTO pivot_test VALUES (2,3,'B');
INSERT INTO pivot_test VALUES (2,67,'C');
COMMIT;

期望的结果将是:

customer_id    Address1    Address2    Address3    Address4    Address5
1                 C            E           A           F           B
2                 C            A           B

2 个答案:

答案 0 :(得分:1)

我会用条件聚合来做到这一点:

select customer_id,
       max(case when seqnum = 1 then address end) as address_1,
       max(case when seqnum = 2 then address end) as address_2,
       max(case when seqnum = 3 then address end) as address_3,
       max(case when seqnum = 4 then address end) as address_4,
       max(case when seqnum = 5 then address end) as address_5
from (select pt.*,
             row_number() over (partition by customer_id order by customer_id) as seqnum
      from pivot_test pt
     ) pt
group by customer_id;

答案 1 :(得分:1)

使用PIVOT

select *
from (
    select 
        customer_id,
        address,
        row_number() over (partition by customer_id order by claims_count desc) rn
    from pivot_test t
)
pivot (
    max(address) for rn in (
        1 as Address1,
        2 as Address2,
        3 as Address3,
        4 as Address4,
        5 as Address5
    )
);

演示:

SQL> select *
  2  from  (
  3    select
  4     customer_id,
  5     address,
  6     row_number() over (partition by customer_id order by claims_count desc) rn
  7    from pivot_test t
  8  )
  9  pivot (
 10    max(address) for rn in (
 11      1 as Address1,
 12      2 as Address2,
 13      3 as Address3,
 14      4 as Address4,
 15      5 as Address5
 16    )
 17  );

CUSTOMER_ID ADDRE ADDRE ADDRE ADDRE ADDRE
----------- ----- ----- ----- ----- -----
          1 C     E     A     F     B
          2 C     A     B

SQL>