如何在表格上使用数据透视表

时间:2015-05-25 14:23:47

标签: sql oracle pivot

我有表格,包括客户,前提,周期和电话号码。如果客户有多个电话号码,那么它应该在同一行但是在不同的列中。

在数据库中:

  Customer   Premise    Phone
------------------------------
C1         P1         Ph1
C1         P1         Ph2
C1         P1         Ph3
C2         P2         Ph1

我想要的:

Customer   Premise    Phone   Phone1  Phone3
-----------------------------------------------
C1         P1         Ph1     Ph2     Ph3
C2         P2         Ph1     {null}  {null}

如何为此编写数据透视表?请帮忙。

1 个答案:

答案 0 :(得分:1)

此查询提供预期输出:

select * from (
  select customer, premise, phone,
    row_number() over (partition by customer order by premise, phone) rn
  from customers)
    pivot (max(phone) phone for rn in (1, 2, 3))

输出:

CUSTOMER  PREMISE  1_PHONE  2_PHONE  3_PHONE
--------  -------  -------  -------  -------
C1        P1       Ph1      Ph2      Ph3
C2        P2       Ph1

SQLFiddle

如果您想要动态数量的手机,请阅读this article