原始表1
SID A B C
2001 80 81 87
2002 60 62 63
2003 72 77 79原始表2
LID TYPE CHN
1 A 语文
4 B 数学
5 C 英语希望出现效果1:
SID 语文 数学 英语
2001 80 81 87
2002 60 62 63
2003 72 77 79效果2:
TMP 2001 2002 2003
语文 80 60 72
数学 81 62 77
英语 87 63 79请高手帮忙下
SID A B C
2001 80 81 87
2002 60 62 63
2003 72 77 79原始表2
LID TYPE CHN
1 A 语文
4 B 数学
5 C 英语希望出现效果1:
SID 语文 数学 英语
2001 80 81 87
2002 60 62 63
2003 72 77 79效果2:
TMP 2001 2002 2003
语文 80 60 72
数学 81 62 77
英语 87 63 79请高手帮忙下
你可以用MAX(DECODE(列,'语文',值))YW 这种形式来写,无非写三遍。
如果不只有这三科,以后肯定会增加。增加内容和数量又不确定,而且又非要用这种方式显示的话。
那么你只能写成动态SQL,通过查询先查出科目的内容,然后使用字符串拼接出 MAX(DECODE(列,'语文',值))YW 这样的形式。
挺麻烦。
SQL> drop table tt1;
Table dropped
SQL> drop table tt2;
Table dropped
SQL> create table tt1(sid number,a number,b number,c number);
Table created
SQL> create table tt2(lid number,type varchar2(10),chn varchar2(10));
Table created
SQL> create or replace procedure tt1_converts authid current_user
2 as
3 v_colname tt2.chn%type;
4 sqlstr varchar2(500);
5 begin
6 for cur in(select column_name from user_tab_cols where table_name='TT1' order by column_id)loop
7 select max(chn) into v_colname from tt2 where type=cur.column_name;
8 sqlstr:=sqlstr||','||cur.column_name;
9 if v_colname is not null then
10 sqlstr:=sqlstr||' "'||v_colname||'"';
11 end if;
12 end loop;
13 execute immediate 'create or replace view v_tt1 as select '||substr(sqlstr,2)||' from tt1';
14 end;
15 /
Procedure created
SQL> insert into tt1
2 select 2001,80,81,87 from dual union all
3 select 2002,60,62,63 from dual union all
4 select 2003,72,77,79 from dual;
3 rows inserted
SQL> insert into tt2
2 select 1,'A','语文' from dual
3 union all select 4,'B','数学' from dual
4 union all select 5,'C','英语' from dual;
3 rows inserted
SQL> execute tt1_converts;
PL/SQL procedure successfully completed
SQL> select * from v_tt1;
SID 语文 数学 英语
---------- ---------- ---------- ----------
2001 80 81 87
2002 60 62 63
2003 72 77 79
SQL>
SQL>
SQL> declare
2 sqlstr varchar2(2000);
3 sqlstr1 varchar2(500);
4 v_tmp varchar2(200);
5 begin
6 for cur in (select column_name
7 from user_tab_cols
8 where table_name = 'TT1'
9 and column_id > 1) loop
10 sqlstr := sqlstr || chr(10) || case when sqlstr is not null then 'union all ' end || 'select ''' || cur.column_name || ''' tmp';
11 sqlstr1 := null;
12 for cur1 in (select sid, rownum rn from tt1) loop
13 sqlstr1 := sqlstr1 || ',max(decode(sid,' || cur1.sid || ',"' ||
14 cur.column_name || '")) "' || cur1.sid || '"';
15 if nvl(length(v_tmp) - length(replace(v_tmp, ',')), 0) < cur1.rn then
16 v_tmp := v_tmp || ',a."' || cur1.sid || '"';
17 end if;
18 end loop;
19 sqlstr := sqlstr || sqlstr1 || ' from tt1';
20 end loop;
21 sqlstr := 'create or replace view v_tt1_1 as select b.chn tmp' || v_tmp ||
22 ' from (' || sqlstr || ')a,tt2 b where a.tmp=b.type';
23 execute immediate sqlstr;
24 end;
25 /
PL/SQL procedure successfully completed
SQL> select * from v_tt1_1;
TMP 2001 2002 2003
---------- ---------- ---------- ----------
语文 80 60 72
数学 81 62 77
英语 87 63 79
SQL>