最近面试遇到了这样一个问题,希望大神能帮助给解答一下:
有这样一个表
Year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1992 1 2.1
1992 2 2.1
1992 3 2.2
查询出来显示这样一个结果:
Year m1 m2 m3
1991 1.1 1.2 1.3
1992 2.1 2.2 2.3
select t.Year, (select amount from table t1 where as t1.Year = t.Year and t1.month = 1) as m1, (select amount from table t1 where as t1.Year = t.Year and t1.month = 2) as m2, (select amount from table t1 where as t1.Year = t.Year and t1.month = 3) as m3 from table as t group by Year
参考行转列
1. 行列转换--普通
假设有张学生成绩表(CJ)如下
Name Subject Result
张三 语文 80
张三 数学 90
张三 物理 85
李四 语文 85
李四 数学 92
李四 物理 82
想变成
姓名 语文 数学 物理
张三 80 90 85
李四 85 92 82
declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = @sql+' from test group by name'
exec(@sql)