Create table test (name char(10),km char(10),cj int)
go
insert test values('张三','语文',80)
insert test values('张三','数学',86)
insert test values('张三','英语',75)
insert test values('李四','语文',78)
insert test values('李四','数学',85)
insert test values('李四','英语',78)
想变成
姓名 语文 数学 英语
张三 80 86 75
李四 78 85 78
declare @sql varchar(8000)
set @sql = 'select name'
select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
from (select distinct km from test) as a
select @sql = @sql+' from test group by name'
exec(@sql)
drop table test
go
insert test values('张三','语文',80)
insert test values('张三','数学',86)
insert test values('张三','英语',75)
insert test values('李四','语文',78)
insert test values('李四','数学',85)
insert test values('李四','英语',78)
想变成
姓名 语文 数学 英语
张三 80 86 75
李四 78 85 78
declare @sql varchar(8000)
set @sql = 'select name'
select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
from (select distinct km from test) as a
select @sql = @sql+' from test group by name'
exec(@sql)
drop table test
解决方案 »
- 请问怎样通过一个表的所拥有的外键,查找到主键所在的表
- 游标中能否用变量语句,在线等
- 数据查询
- 我的mssql2000在本机上企业管理器和查询都能连接,可是在别的机器上访问不到,为什么啊
- distinct问题?
- sql server同步(replication )的问题,急,望大家帮个忙,谢谢。。。
- sql 空字符的默认值
- 为什么SQLServer里的删除触发器在多条记录一起删除时,只会触发一次?
- sql help document!
- 多日未决的问题,拜托你给个答复:请问在win2000的服务里设置sql的允许桌面交互是什么意思?请问如何当sql表里数据更新了就自动通知VB刷
- 各位兄弟刚才的问题还差一点忘问了,谢谢帮助解决
- 请问
insert into A
select 'a',1
union all select 'b',2
select * from A
Declare @S Varchar(8000)
Select @S = ''
Select @S = @S + ', max(Case NAME When ''' + NAME + ''' Then NUMBER Else 0 End) As [' + NAME + ']'
From A Group By NAME
Select @S = 'Select ' + Stuff(@S, 1, 1, '') + ' From A'
EXEC(@S)