table1:
-------------------------------------------------
f001 f002 f003
1998 A 1
1999 A 1
2000 B 1
2005 C 1
----------------------------------------------
TBALE2:
-------------------------------------------
F001 F002
A 上海
B 深圳
C 广州
-------------------------------------------
table2的记录数未知要求结果:
-------------------------
F001 A B C D ---------
1998 1 0 0
1999 1 0 0
2000 0 1 0
2005 0 0 1
-------------------------------------------------
f001 f002 f003
1998 A 1
1999 A 1
2000 B 1
2005 C 1
----------------------------------------------
TBALE2:
-------------------------------------------
F001 F002
A 上海
B 深圳
C 广州
-------------------------------------------
table2的记录数未知要求结果:
-------------------------
F001 A B C D ---------
1998 1 0 0
1999 1 0 0
2000 0 1 0
2005 0 0 1
f001 varchar(20),
f002 varchar(20),
f003 number)insert into xhb_test
select 1998 , 'A' , 1 from dual
union
select 1999 , 'A' , 1 from dual union
select 2000 , 'B' , 1 from dual union
select 2005 , 'C' , 1 from dual select f001,decode(f002,'A',f003,0) as A,decode(f002,'B',f003,0) as B,decode(f002,'C',f003,0) as C,decode(f002,'D',f003,0) as D from xhb_test
-------------------------------------------------
f001 f002 f003
1998 A 1
1999 A 1
2000 B 1
2005 C 1
f002的值类型确定的话就可以用decode实现,如楼上:
如果f002的类型不确定就复杂多拉!
如
student subject grade
---------------------------
student1 语文 80
student1 数学 70
student1 英语 60
student2 语文 90
student2 数学 80
student2 英语 100
……
转换为
语文 数学 英语
student1 80 70 60
student2 90 80 100
……
语句如下:
select student,sum(decode(subject,'语文', grade,null)) "语文",
sum(decode(subject,'数学', grade,null)) "数学",
sum(decode(subject,'英语', grade,null)) "英语"
from table
group by student
case F002 when 'A' then 1 else 0 end A,
case F002 when 'B' then 1 else 0 end B,
case F002 when 'C' then 1 else 0 end C,
case F002 when 'D' then 1 else 0 end D
from Table