首页 新闻 会员 周边

SQL语句的问题

1
悬赏园豆:10 [已解决问题] 解决于 2016-03-04 17:08

最近面试遇到了这样一个问题,希望大神能帮助给解答一下:

 有这样一个表

 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

SQL
IT小伙儿的主页 IT小伙儿 | 初学一级 | 园豆:11
提问于:2016-03-04 16:36
< >
分享
最佳答案
0
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
收获园豆:10
刘宏玺 | 专家六级 |园豆:14020 | 2016-03-04 17:00
其他回答(1)
0

参考行转列

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)

Rich.T | 园豆:3440 (老鸟四级) | 2016-03-04 16:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册