zoukankan      html  css  js  c++  java
  • SQLServer2008 行转列3

    with  a as (
    select 日期,学号,名字, '语文' as 科目,语文 as 分数
    from tsco
    union all
    select 日期,学号,名字, '数学' as 科目,数学 as 分数
    from tsco
    union all
    select 日期,学号,名字, '英语' as 科目,英语 as 分数
    from tsco
    )
    select 学号,名字,科目,
    	max(case when 日期='2014/10/1'  then 分数 end) as '2014/10/1' ,
    	max(case when 日期='2014/11/1'  then 分数 end) as '2014/11/1' ,
    	max(case when 日期='2014/12/1'  then 分数 end) as '2014/12/1' 
    from a
    group by 学号,名字,科目
    

     以上写的不对的地方多多指教

    以下是高手写的:

    if OBJECT_ID('数据') is not null drop table 数据
     
    create table 数据(日期 varchar(10),
                      学号 varchar(5), 
                      名字 varchar(4),
                      语文 numeric(3,0),
                      数学 numeric(3,0),
                      英语 numeric(3,0))
    insert into 数据 select '2014/10/1',1,'甲',98,80,60
    insert into 数据 select '2014/10/1',2,'甲',100,40,70
    insert into 数据 select '2014/10/1',3,'丙',50,20,100
    insert into 数据 select '2014/11/1',1,'甲',90,80,60
    go
    declare @i varchar(8000),@j as varchar(8000)
    set @i=''
    set @j=''
    select @i=@i+',['+日期+']' from 数据 group by 日期
    select @j='select * 
    from (select 日期,学号,名字,语文 as 成绩,''语文'' as 科目 from 数据 union all
    select 日期,学号,名字, 数学 as 成绩,''数学'' as 科目 from 数据 union all
    select 日期,学号,名字, 英语 as 成绩,''英文'' as 科目 from 数据) as bb
    pivot (sum(成绩) for 日期 in ('+stuff(@i,1,1,'')+')) as bb'
     
    exec(@j)
    
  • 相关阅读:
    Linux负载均衡--LVS(IPVS)主要算法实现分析
    使用alarm控制阻塞connect()超时的示例
    使用select控制非阻塞connect()超时的示例
    再出发
    nulls_hlist原理 和 tcp连接查找
    linux支持大容量硬盘
    Nmap扫描原理(下)
    linux常用命令
    Linux下面自动清理超过指定大小的文件
    Memcached介绍
  • 原文地址:https://www.cnblogs.com/emmy/p/4308607.html
Copyright © 2011-2022 走看看