再论oracle之行列转换

之前我曾经针对行列转换写了一篇文章,具体地址:http://honeybinshun.iteye.com/blog/1669038

不过,最近在逛论坛的时候,发现了oracle11g自带该功能,具体如下:

--创建测试表,初始数据如下:

201301 017 YDYH0366 88360
201302 010 YDYH0366 49308
201302 030 YDYH0366 21226
201302 084 YDYH0366 18723
201302 111 YDYH0366 1259016
201301 075 YDYH0366 3091
201302 097 YDYH0366 16863
201301 079 YDYH0366 3090
201301 018 YDYH0366 11892
201302 013 YDYH0366 30609
201301 088 YDYH0366 11375

create table M_TEST_T
(
  MONTH_ID  VARCHAR2(10),
  PROV_ID   VARCHAR2(6),
  KPI_CODE  VARCHAR2(10),
  KPI_VALUE NUMBER
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
  select * from m_test_t

--实现行转列

select * from m_test_t pivot(sum(kpi_value) for prov_id in('011' as "011",'013' as "013"));

--结果如下:

month_id    kpi_code           011           013

201301      YDYH0357  
201301      YDYH0382       434294    154873
201301      YDYH0384       82016        1082

 create table m_test_unpivot as select * from m_test_t pivot(sum(kpi_value) for prov_id in('011' as "011",'013' as "013"));
select * from m_test_unpivot unpivot(kpi_value for prov_id in("011","013"));

详见oracle11g新特性pivot和unpivot解释(oracle官方文档):

http://www.oracle.com/technetwork/cn/articles/11g-pivot-101924-zhs.html

你可能感兴趣的:(oracle)