Home >Database >Mysql Tutorial >Oracle 行转列 的写法

Oracle 行转列 的写法

WBOY
WBOYOriginal
2016-06-07 17:15:371319browse

Oracle 行转列 的写法: /* DROP TABLE FOO; */ /**创建一张演示的表**/ CREATE TABLE FOO ( BBBID NUMBER(2), --主键

Oracle 行转列 的写法:

/*

DROP TABLE FOO;

*/

/**创建一张演示的表**/

CREATE TABLE FOO (

    BBBID NUMBER(2),       --主键

    DEPID NUMBER(2),      --单位编号

    AAC006 VARCHAR2(1)  --性别  1男  2女  0未知

    CONSTRAINT CK_AAC006 CHECK (AAC006 = '1' OR AAC006 ='2' OR AAC006 ='0')

);

/**插入用于测试的数据**/

INSERT INTO FOO VALUES(1,1,'1');

INSERT INTO FOO VALUES(2,1,'0');

INSERT INTO FOO VALUES(3,1,'2');

INSERT INTO FOO VALUES(4,1,'2');

INSERT INTO FOO VALUES(5,2,'1');

INSERT INTO FOO VALUES(6,2,'0');

INSERT INTO FOO VALUES(7,2,'2');

INSERT INTO FOO VALUES(8,2,'2');

INSERT INTO FOO VALUES(9,3,'2');

INSERT INTO FOO VALUES(10,3,'2');

INSERT INTO FOO VALUES(11,3,'2');

/**

目标:对该表进行行转列,要得到如下结果集:

depid 男 女 未知

 1  2

 1  2

 0  3

*/

/**原始的数据**/

SELECT * FROM FOO;

/**按照性别码表取值,将FOO.AAC006转化为3列之后的值**/

SELECT DEPID,

    DECODE(AAC006,'0',1,0) "男",

    DECODE(AAC006,'1',1,0) "女",

    DECODE(AAC006,'2',1,0) "未知"

 FROM  FOO;

 /**在上一个结果集上进行加工,就得到行转列的结果!**/

 SELECT DEPID,

    SUM(DECODE(AAC006,'0',1,0)) "男",

    SUM(DECODE(AAC006,'1',1,0)) "女",

    SUM(DECODE(AAC006,'2',1,0)) "未知"

 FROM  FOO

 GROUP BY DEPID;


 /**

 总结(czw  20120624):

 行转列,,其实就是将某一个字段,按照码值拆分为若干个字段,最后通过聚集函数得到相应的值。

 **/

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn