请教一个SQL语句(30分)

  • 主题发起人 主题发起人 flyskylf
  • 开始时间 开始时间
F

flyskylf

Unregistered / Unconfirmed
GUEST, unregistred user!
我用的是SQLServer2000表结构如下:
f1 f2 //列名
1 a
2 b
3 c
4 d
5 e
变换成:
a b c d e //列名
1 2 3 4 5
 
观望中,不知道
 
select sum(a) as a,sum(b) as b ,sum(c) as c ,sum(d) as d,sum(e) as e
from (
select 'aa' as aa,case f2 when 'a' then f1 else 0 end as a,
case f2 when 'b' then f1 else 0 end as b,
case f2 when 'c' then f1 else 0 end as c,
case f2 when 'd' then f1 else 0 end as d,
case f2 when 'e' then f1 else 0 end as e
from table1) abc
group by abc.aa
 
这个问题在大富翁里问了n遍了,怎么都不去找啊,搞程序的不能懒。。。
 
/*測試數據*/
create table t (f1 int,f2 varchar(2))
insert into t
select 1,'a'
union
select 2,'b'
union
select 3,'c'
union
select 4,'d'
union
select 5,'e'

/*語句*/
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when f2='''+f2+''' then f1 end) as '+f2 from T group by f2
set @sql='select '+stuff(@sql,1,1,'')+' from T'
exec(@sql)

/*The result:*/
a b c d e
----------- ----------- ----------- ----------- -----------
1 2 3 4 5
 
接受答案了.
 

Similar threads

D
回复
0
查看
775
DelphiTeacher的专栏
D
D
回复
0
查看
679
DelphiTeacher的专栏
D
D
回复
0
查看
670
DelphiTeacher的专栏
D
D
回复
0
查看
859
DelphiTeacher的专栏
D
后退
顶部