前段时间面试了几家公司,基本上都有关于行转列的问题,今天总结一下,作为自己复习备忘,也给需要的朋友参考,废话少说,开始...
case语法结构,如下:
case when expression1 then result1 when expression2 then result2...else result end)
decode语法结构:
decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n, default)
case和decode比较:
1、decode Oracle 特有,case属于sql标准;
2、decode 只能用做相等判断,但是可以配合sign函数进行大于,小于,等于的判断,CASE可用于=,>=,,is null,is not null 等的判断;
3、decode 使用起来比较简洁,case虽然复杂但更为灵活
例子:
create table students(
id int,
name varchar2(30),
subject varchar2(20),
grade number);
********************************************************
SQL> desc students;
Name Null? Type
----------------- -------- ------------
ID NUMBER(38)
NAME VARCHAR2(30)
SUBJECT VARCHAR2(20)
GRADE NUMBER
********************************************************
insert into students values(1,'ZORRO','language',70);
insert into students values(2,'ZORRO','mathematics',80);
insert into students values(3,'ZORRO','english',75);
insert into students values(4,'SEKER','language',65);
insert into students values(5,'SEKER','mathematics',75);
insert into students values(6,'SEKER','english',60);
insert into students values(7,'BLUES','language',60);
insert into students values(8,'BLUES','mathematics',90);
insert into students values(9,'PG','mathematics',80);
insert into students values(10,'PG','english',90);
*********************************************************
SQL> select * from students
ID NAME SUBJECT GRADE
---- ---------- ------------- ----------
1 ZORRO language 70
2 ZORRO Mathematics 80
3 ZORRO english 75
4 SEKER language 65
5 SEKER Mathematics 75
6 SEKER english 60
7 BLUES language 60
8 BLUES Mathematics 90
9 PG Mathematics 80
10 PG english 90
*********************************************************
以上是题目的表结构及数据,写出最少两种结构的语句显示如下所示信息:
select name,
sum(case when subject='language' then grade else 0 end) language,
sum(case when subject='Mathematics' then grade else 0 end) Mathematics,
sum(case when subject='english' then grade else 0 end) english
from students group by name
/
select name,
sum(decode(subject,'language',grade,0)) language,
sum(decode(subject,'Mathematics',grade,0)) Mathematics,
sum(decode(subject,'english',grade,0)) english
from students group by name
/
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/24433396/viewspace-743757/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/24433396/viewspace-743757/