|
1、建表
- 1create table kecheng
- 2 (
- 3 id NUMBER,
- 4 name VARCHAR2(20),
- 5 course VARCHAR2(20),
- 6 score NUMBER
- 7 );
- 8 insert into kecheng (id, name, course, score)
- 9 values (1, '张三', '语文', 67);
- 10 insert into kecheng (id, name, course, score)
- 11 values (1, '张三', '数学', 76);
- 12 insert into kecheng (id, name, course, score)
- 13 values (1, '张三', '英语', 43);
- 14 insert into kecheng (id, name, course, score)
- 15 values (1, '张三', '历史', 56);
- 16 insert into kecheng (id, name, course, score)
- 17 values (1, '张三', '化学', 11);
- 18 insert into kecheng (id, name, course, score)
- 19 values (2, '李四', '语文', 54);
- 20 insert into kecheng (id, name, course, score)
- 21 values (2, '李四', '数学', 81);
- 22 insert into kecheng (id, name, course, score)
- 23 values (2, '李四', '英语', 64);
- 24 insert into kecheng (id, name, course, score)
- 25 values (2, '李四', '历史', 93);
- 26 insert into kecheng (id, name, course, score)
- 27 values (2, '李四', '化学', 27);
- 28 insert into kecheng (id, name, course, score)
- 29 values (3, '王五', '语文', 24);
- 30 insert into kecheng (id, name, course, score)
- 31 values (3, '王五', '数学', 25);
- 32 insert into kecheng (id, name, course, score)
- 33 values (3, '王五', '英语', 8);
- 34 insert into kecheng (id, name, course, score)
- 35 values (3, '王五', '历史', 45);
- 36 insert into kecheng (id, name, course, score)
- 37 values (3, '王五', '化学', 1);
- 38 commit;
复制代码 2、Decode方式
- SELECT ID,NAME,
- SUM(DECODE(course,'语文',score,0)) 语文,--这里使用max,min都可以
- SUM(DECODE(course,'数学',score,0)) 数学,
- SUM(DECODE(course,'英语',score,0)) 英语,
- SUM(DECODE(course,'历史',score,0)) 历史,
- SUM(DECODE(course,'化学',score,0)) 化学
- FROM kecheng
- GROUP BY ID ,NAME
复制代码
3、case方式
- <font face="宋体" size="2">SELECT ID,NAME,
- MAX(CASE WHEN course='语文' THEN score ELSE 0 END) 语文,
- MAX(CASE WHEN course='数学' THEN score ELSE 0 END) 数学,
- MAX(CASE WHEN course='英语' THEN score ELSE 0 END) 英语,
- MAX(CASE WHEN course='历史' THEN score ELSE 0 END) 历史,
- MAX(CASE WHEN course='化学' THEN score ELSE 0 END) 化学
- FROM kecheng
- GROUP BY ID ,NAME</font>
复制代码
4、wmsys.wm_concat行列转换函数
- <font face="宋体" size="2">SELECT ID,NAME,
- wmsys.wm_concat(course || ':'||score) course
- FROM kecheng
- GROUP BY ID ,NAME;</font>
复制代码
5、使用over(partition by t.u_id)用法
- SELECT NAME,
- wmsys.wm_concat(course ||score) OVER (PARTITION BY NAME)
- FROM kecheng
复制代码 6、使用plsql
- DECLARE
- --存放最终的SQL
- LV_SQL VARCHAR2(3000);
- --存放连接的SQL
- SQL_COMMOND VARCHAR2(3000);
- --定义游标
- CURSOR CUR IS
- SELECT COURSE FROM KECHENG GROUP BY COURSE;
- BEGIN
- --定义查询开头
- SQL_COMMOND := 'SELECT NAME ';
- FOR I IN CUR LOOP
- --将结果相连接
- SQL_COMMOND := SQL_COMMOND || ' ,SUM(DECODE(course,''' || I.COURSE ||
- ''',score,0)) ' || I.COURSE;
- DBMS_OUTPUT.PUT_LINE(SQL_COMMOND);
- END LOOP;
- SQL_COMMOND := SQL_COMMOND || ' from KECHENG group by name';
- LV_SQL := 'INSERT INTO temp_ss ' || SQL_COMMOND;
- DBMS_OUTPUT.PUT_LINE(LV_SQL);
- EXECUTE IMMEDIATE LV_SQL;
- END;
复制代码
|
|