Oracle 多行转多列,列值转为列名

前段时间做调查问卷,客户创建自定义问卷内容,包括题目和选项内容;

之后需要导出问卷明细,,,,麻烦来咯

于是到网上到处搜索,没有直接结果;于是又找各种相似的,,终于功夫不负有心人

然后最终自己写出来了,decode才是核心

废话不多说,看图

需求示例图表:

Oracle 多行转多列,列值转为列名

存储过程,嘿嘿:

 create or replace procedure NAG_QUESTIONERSULT_EXP(
V_QID in number,
C_Title out sys_refcursor,
C_Data out sys_refcursor
)
as
/*
导出调查问卷资答案数据
Auth:lzpong 2015/09/01
*/
cursor dusers is --列信息
select qss.qss_id,nvl(qss.qss_title,substr(qs.qs_title,0,20)) QSS_TITLE from nag_questions qs,nag_questionss qss
where qss.qss_qs_id=qs.qs_id and qs.qs_q_id=V_QID
order by qs.qs_order,qss.qss_order;
strSql varchar2(10000);
begin
for ur in dusers loop
strSql:=strSql||'wm_concat(decode(QR_QSS_ID,'''||ur.qss_id||''',QR_QSS_DES,null)) as "'||ur.qss_title||'",';
end loop;
open C_Data for
'select QR_ID,QR_AGENTID,max(QR_CREATEDATE) QR_CREATEDATE,'||
substr(strSql,0,length(strSql)-1)
||'from (
select QR_QS_ID,QR_QSS_ID QR_QSS_ID,''(√)''||QR_QSS_DES QR_QSS_DES, QR_CREATEDATE,QR_U_ID,QR_AGENTID,QR_ID
from nag_questionresult,nag_questions where qr_qs_id=qs_id and qs_q_id='||V_QID||'
order by QR_ID
)
group by QR_ID,QR_AGENTID';
open C_Title for
select q.q_id,q.q_title,q.q_des,qs.qs_id,qs.qs_title ,(select count(qss_id) from nag_questionss qss where qss.qss_qs_id=qs.qs_id) qs_cols
from nag_question q,nag_questions qs where q.q_id=qs.qs_q_id and q.q_id=V_QID
order by q.q_id,qs.qs_order;
end;

存储过程

实际数据:

Oracle 多行转多列,列值转为列名 Oracle 多行转多列,列值转为列名

结果:

Oracle 多行转多列,列值转为列名

转载请注明来自:lzpong

URL:http://www.cnblogs.com/lzpong/p/4778022.html

上一篇:“ORA-06550: 第 1 行, 第 7 列”解决方法


下一篇:【收藏】SQL多行变一列