SQL面试题之一

某年某月某日某司出如下题:


月份    部门    绩效
一月	  01	    10
一月	  02	    5
二月	  02	    8
二月	  01	    3
三月	  03	    2
三月	  03	    4


要得到如下结果:

部门    一月   二月   三月
01	   10	   3	
02	   5	   8	
03			          6


当时写得不好,现重写一下(以下实现为oracle数据库):

create table test_1(
月份 varchar(6),
部门 varchar(10),
绩效 int
)
insert into test_1(月份,部门,绩效) values('一月','01',10)
insert into test_1(月份,部门,绩效) values('一月','02',5);
insert into test_1(月份,部门,绩效) values('二月','02',8);
insert into test_1(月份,部门,绩效) values('二月','01',3);
insert into test_1(月份,部门,绩效) values('三月','03',2);
insert into test_1(月份,部门,绩效) values('三月','03',4);


实现:
[color=red]
select 部门,
sum(decode(月份,'一月',绩效)) as 一月,
sum(decode(月份,'二月',绩效)) as 二月,
sum(decode(月份,'三月',绩效)) as 三月
from test_1 group by 部门
[/color]

最后的话:iteye,你的编辑组件真NND难用啊

猜你喜欢

转载自coderanch.iteye.com/blog/1564073