oracle行列转换

1、固定列数的行列转换

如:

student subject grade
---------------------------
student1 语文 80
student1 数学 70
student1 英语 60
student2 语文 90
student2 数学 80
student2 英语 100
……
转换为
语文 数学 英语
student1 80 70 60
student2 90 80 100

……
语句如下:
  1. selectstudent,sum(decode(subject,'语文',grade,null))"语文",
  2. sum(decode(subject,'数学',grade,null))"数学",
  3. sum(decode(subject,'英语',grade,null))"英语"
  4. fromtable
  5. groupbystudent


2、不定列行列转换


c1 c2
--------------
1 我
1 是
1 谁
2 知
2 道
3 不
……

转换为
1 我是谁
2 知道
3 不
这一类型的转换必须借助于PL/SQL来完成,这里给一个例子

  1. CREATEORREPLACEFUNCTIONget_c2(tmp_c1NUMBER)
  2. RETURNVARCHAR2
  3. IS
  4. Col_c2VARCHAR2(4000);
  5. BEGIN
  6. FORcurIN(SELECTc2FROMtWHEREc1=tmp_c1)LOOP
  7. Col_c2:=Col_c2||cur.c2;
  8. ENDLOOP;
  9. Col_c2:=rtrim(Col_c2,1);
  10. RETURNCol_c2;
  11. END;
  1. SQL>selectdistinctc1,get_c2(c1)cc2fromtable;

看到这里,已经有了解决思路了,在oracle中建一个function,代码如下:

  1. CREATEORREPLACEFUNCTIONget_ver(tmp_boinstidVARCHAR2)
  2. RETURNVARCHAR2
  3. IS
  4. versVARCHAR2(100);
  5. BEGIN
  6. FORcurIN(SELECTpln_verFROMPMS_BUDGET_PLANWHEREboinst_id=tmp_boinstidorderbyis_all_run)LOOP
  7. vers:=vers||cur.pln_ver||',';
  8. ENDLOOP;
  9. vers:=rtrim(vers,1);
  10. RETURNvers;
  11. ENDget_ver;


然后使用这个函数来查询就可以了,

  1. SELECTdistinctp.pln_name,p.pln_year,get_ver(boinst_id)FROMPMS_BUDGET_PLANpWHEREp.pln_type=20andp.del_flag=-1andboinst_idisnotnull

需要注意的是,由于函数中也使用了sql,所以这个方法不太适合大数据量的查询,使用时应注意。

你可能感兴趣的:(oracle)