利用Oracle rownum完成行轉列一例
2024-08-29 13:34:12
供稿:網友
一、需求背景: 表A:CREATE TABLE T_SMCOMMONMSG ( FXH NUMBER, FTYPE NUMBER, FMSG_CONTENT VARCHAR2(1024 BYTE) ) 表B:CREATE TABLE T_SMYL_COMMONSND ( FXH NUMBER, FMSG_CONTENT1 VARCHAR2(1024 BYTE), FMSG_CONTENT2 VARCHAR2(1024 BYTE) ) 表A中的原始記錄如下: FXH FTYPE FMSG_CONTENT ------ -------- -------------- 98 0 msg1 99 0 msg2 100 0 msg3 101 0 msg4 表B中的現有記錄如下: FXH FMSG_CONTENT1 FMSG_CONTENT2 ------- ---------------- -------------- 1 空 空 2 空 空 需求:現要求將表A中的記錄轉換成如下格式的表B中的記錄: FXH FMSG_CONTENT1 FMSG_CONTENT2 ------ ---------------- -------------- 1 msg1 msg2 2 msg3 msg4 注:表A是一個包含了多種FTYPE類型的信息表,其中FTYPE=0的信息就是轉換的原始信息,序號從98開始 表B是一個包含了一種FTYPE類型的信息表,其序號從1開始 二、解決方案: 1.嘗試使用如下SQL語句:update t_smyl_commonsnd a set a.fmsg_content1 = (select fmsg_content from t_smcommonmsg b where b.ftype = 0 and mod(b.fxh,2) =0)
錯誤原因:子查詢的結果是一個結果集,不能將結果集賦給一條記錄的某個字段 2.嘗試使用如下SQL語句: update t_smyl_commonsnd a set a.fmsg_content1 = (select fmsg_content from t_smcommonmsg b where b.ftype = 0 and mod(b.fxh,2) =0 and a.fxh = b.fxh -97) 但執行: select * from t_smyl_commonsnd;結果為: FXH FMSG_CONTENT1 FMSG_CONTEN2
-------- --------------- --------------
1 msg1
2
3 msg2
4
5 msg3 錯誤原因:子查詢中對與表A中FXH值為偶數的記錄,其返回值為NULL,所以偶數行的字段都為空 3.嘗試使用如下SQL語句: --更新字段:FMSG_CONTENT1 update t_smyl_commonsnd a set a.fmsg_content1 = (select fmsg_content from (select rownum id, fmsg_content from (select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 0 order by fxh asc) v1 ) v2 Where a.fxh = v2.id); --更新字段:FMSG_CONTENT2 update t_smyl_commonsnd a set a.fmsg_content2 = (select fmsg_content from (select rownum id, fmsg_content from (select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 1 order by fxh asc) v1 ) v2 where a.fxh = v2.id);
返回結果如下: FXH FMSG_CONTENT1 FMSG_CONTENT2----- --------------- --------------- 1 msg1 msg2 2 msg3 msg4 更新成功! 分析: 1)。 找出表A中所有FTYPE=0且FXH為雙數的記錄,也即是FMSG_CONTENT1字段的目標值select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 0 order by fxh asc 2)。給篩選的結果加上Rownum,和表B中的記錄一一對應 select rownum id, fmsg_content from (select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 0 order by fxh asc) v1
3)。找出視圖V1中ID值和表B的FXH號值對應的記錄 select fmsg_content from (select rownum id, fmsg_content from (select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 0 order by fxh asc) v1 ) v2 where a.fxh = v2.id 4)。更新記錄的值: update t_smyl_commonsnd a set a.fmsg_content1 = (select fmsg_content from (select rownum id, fmsg_content from (select fmsg_content from t_smcommonmsg where ftype = 0 and mod(fxh, 2) = 0 order by fxh asc) v1 ) v2 where a.fxh = v2.id);
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1476118