想鸟一样飞翔

专注于php开发。对c++也很有兴趣!!!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

接上篇,要是课程我不知道怎么办呢?“办法比困难多”,考虑后得出一个解决方法。

就是用字符串拼接的方法,把所有的课程都拼接起来。不是很繁琐。代码如下:


USE TEMPDB

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'TEMPDB.[dbo].[#temptable]'AND type in (N'U'))
begin
    
drop table #temptable
end
create table #temptable
(
 ID 
int ,
 course 
varchar(10),
 Point 
int
)

insert into #temptable
select 1 ,'语文',87
union all
select 1 ,'数学',98
union all
select 2,'语文',54
union all
select 2,'化学',97
union all
select 2,'数学',92
union all
select 4,'数学',86
union all
select 5 ,'数学',65
union all
select 6,'语文',76
union all
select 6,'数学',76
union all
select 6,'化学',76

select * from #temptable

declare @str varchar(2000)
set @str = ' select ID '
select @str = @str + '  ,  max(case when course = ''' + course +''' then Point else 0 end )  as   ''' + course + '''' 
from  (select distinct course from #temptable) A  
set @str  = @str + ' from #temptable group by ID '
print @str

exec (@str)

 

 

解决啦,说真的这个不是很复杂的问题, 刚要高兴,有哥们说这种问题在sql2005中很见到就能解决。

简单调查下,发现两个关键字PIVOT/UNPIVOT,可以轻松实现行列转换的需求。 

看来得继续前进啦,看看sql2005如何简单实现的。(未完待续)

posted on 2009-04-22 00:52  redfox  阅读(287)  评论(0编辑  收藏  举报