1. 程式人生 > >Oracle pivot行轉列

Oracle pivot行轉列

行轉列語法為pivot(聚合函式 for 列名 in(型別)): pivot ( sum ( planqty ) for plantype in ( 'in', 'out' ) )

1.建立測試表格

CREATE TABLE XXXMGR.FAB_BSFACTORYDAILYPLAN
(
  FACTORYNAME      VARCHAR2(40 BYTE),
  PRODUCTSPECNAME  VARCHAR2(40 BYTE),
  PRODUCTTYPE      VARCHAR2(40 BYTE),
  PLANDATE         VARCHAR2(40 BYTE),
  PLANTYPE         VARCHAR2(40 BYTE),
  PLANQTY          VARCHAR2(40 BYTE),
  LASTEVENTUSER    VARCHAR2(40 BYTE),
  LASTEVENTTIME    DATE,
  LASTEVENTNAME    VARCHAR2(40 BYTE)
)
TABLESPACE ODS_XXX_DAT
;


CREATE UNIQUE INDEX XXXMGR.BSFACTORYDAILYPLAN_PK ON XXXMGR.FAB_BSFACTORYDAILYPLAN
(FACTORYNAME, PRODUCTSPECNAME, PRODUCTTYPE, PLANDATE, PLANTYPE)
TABLESPACE ODS_XXX_IDX
;


ALTER TABLE XXXMGR.FAB_BSFACTORYDAILYPLAN ADD (
  CONSTRAINT BSFACTORYDAILYPLAN_PK
  PRIMARY KEY
  (FACTORYNAME, PRODUCTSPECNAME, PRODUCTTYPE, PLANDATE, PLANTYPE)
  USING INDEX XXXMGR.BSFACTORYDAILYPLAN_PK
  ENABLE VALIDATE);

2.行轉列:in、out轉為列

SELECT * FROM
(SELECT 
     FACTORYNAME
    ,PRODUCTSPECNAME
    ,PRODUCTTYPE
    ,PLANDATE
    ,PLANTYPE
    ,PLANQTY
FROM FAB_BSFACTORYDAILYPLAN)
PIVOT(SUM(PLANQTY) FOR PLANTYPE IN ('IN' INQTY, 'OUT' OUTQTY)) 

列轉行unpivot