日期:2014-05-17 浏览次数:21006 次
數據 create table TANJOTEST ( STUDENT VARCHAR2(20), COURSE VARCHAR2(20), SCORE NUMBER ); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('張三', '語文',80); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('張三', '數學',90); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('張三', '英語',50); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('李四', '語文',40); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('李四', '數學',50); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('李四', '英語',60); INSERT INTO tanjotest(STUDENT, COURSE,SCORE)VALUES('王五', '數學',100); 方法參考: 方法一: SELECT STUDENT, MAX(decode(COURSE,'語文',SCORE,0)) 語文, MAX(decode(COURSE,'數學',SCORE,0)) 數學, MAX(decode(COURSE,'英語',SCORE,0)) 英語, SUM(SCORE) total FROM tanjotest GROUP BY STUDENT; 方法二: SELECT STUDENT, MAX(decode(COURSE,'語文',SCORE,0)) 語文, MAX(decode(COURSE,'數學',SCORE,0)) 數學, MAX(decode(COURSE,'英語',SCORE,0)) 英語, SUM(SCORE) total FROM tanjotest GROUP BY STUDENT;
------解决方案--------------------
--我感觉你这只是你总需求的一部分,因为你少了年份,或者说比如表里存的不只是6月份的数据,等等情况,你还没说清楚, --就针对你说的只有6月份数据,这里写的存储过程有个输入参数月份,方便你后续扩展 create or replace procedure row_to_col_func( v_rq in varchar2 ,cur out sys_refcursor ) as sqlstr varchar2(3000):='select a.custno '; begin for rs in ( with t as( select to_date(v_rq,'mm') mon from dual ) select to_char(mon+level-1,'mm/dd') new_rq from t connect by level<=to_char(last_day(mon),'dd') ) loop sqlstr:=sqlstr||chr(10)||','||'max(decode(a.rq,'''||rs.new_rq||''',a.quantity,0)) as "'||rs.new_rq||'"'; end loop ; sqlstr:=sqlstr||chr(10)||'from tab a group by a.custno ' ; open cur for sqlstr; end row_to_col_func; /