求教一道sql面试题

来源:百度知道 编辑:UC知道 时间:2024/06/01 12:51:55
year month total
1996 1 3000
1996 3 4000
1996 7 5000
1997 3 4000
1997 6 3000
.
.
year m1,m2,m3,m4

year 为年,m1等为季度,要求按上行输出
这道题能用标准sql作吗?

这种需求一般用存储过程写,还好你这里是季度,如果列数较多,那么使用单条SQL难度非常大。

select year,
sum(case when month in( 1,2,3) then total else 0 end) m1,
sum(case when month in( 4,5,6) then total else 0 end) m2,
sum(case when month in( 7,8,9) then total else 0 end) m3,
sum(case when month in( 10,11,12) then total else 0 end) m4
from tab
group by year

declare @sql varchar(10)
set @sql = 'select Year'
select @sql = @sql + ',sum(case month when '''+month+''' then Result end) ['+month+']'
from (select distinct month from tablename) as a
select @sql = @sql+' from tablename group by year'
exec(@sql)

鉴于这0分也没给出相应的字段,给你个提示好了,用转置函数Pivot行列转换