sql行变列

1,将某一行转为列,作用:

如果我们在输入成绩时,一般要按学号,学期,课程号,成绩来输入,但是,我们要打印全班的成绩里就是要把课号改为列了,就如果上面的,那样该怎么做呀 ?

比如:
个人成绩表:
学号  课号   成绩
01   01    80
01   02    79
01   03    88
02   01    87
02   02    77
02   03    68

用SQL把上表转换为:
学号  课号01  课号02  课号03
01   80     79    88
02   87     77    68

---------建表----------
create table tab_score
(
    bid int identity(0,1) primary key ,--流水号
    sid varchar(20) not null,--学生号
    cid varchar(20) not null,--课程号
    score int--成绩
)
insert into tab_score select's01','c01','90' union all select 's01','c02','92' union all select 's01','c03','93'
                  union all select 's02','c01','81' union all select 's02','c02','82'

/*---固定列的写法,后面的写法将是根据有几个课程id来动态组装中间的sum语句,然后加上头尾就成了,
理解了这种'静态'写法,剩下的只是'动态'组装中间sum语句的工作----*/
select * from tab_score
select sid,sum(case cid when 'c01' then score else '0' end) as 'c01',
       sum(case cid when 'c02' then score else '0' end) as 'c02',
           sum(case cid when 'c03' then score else '0' end) as 'c03'          
  from tab_score group by sid         
-----'动态'列的写法,定义一个变量来组装中间的sum语句,其中用到子查询表(原来不用这方法一直会出现重复列)-------   
declare @s varchar(1000)
set @s=''
select  @s=@s+', sum(case cid when '+''''+ a.cid+''''+' then score else ''0'' end) as '+''''+a.cid+'''' 
  from ( select distinct cid from tab_score) a
print @*
**ec('select sid'+@s+'from tab_score group by sid')

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/deadshot123/archive/2006/03/08/618716.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值