• SQLServer 实现行转列


    create table AllScore(
    
    id int identity(1,1) primary key,--主键
    stu_name varchar(20),--学生名
    category varchar(20),--学科
    record float,--成绩
    )
    /*插入数据*/
    insert into AllScore(stu_name,category,record)values('刘德华','Chinese',100)
    insert into AllScore(stu_name,category,record)values('刘德华','English',95)
    insert into AllScore(stu_name,category,record)values('刘德华','Mathmatics',98)
    
    insert into AllScore(stu_name,category,record)values('施瓦辛格','Chinese',90)
    insert into AllScore(stu_name,category,record)values('施瓦辛格','English',95)
    insert into AllScore(stu_name,category,record)values('施瓦辛格','Mathmatics',14)
    
    insert into AllScore(stu_name,category,record)values('太上老君','Chinese',70)
    insert into AllScore(stu_name,category,record)values('太上老君','English',95)
    insert into AllScore(stu_name,category,record)values('太上老君','Mathmatics',57)
    
    insert into AllScore(stu_name,category,record)values('毕达哥拉斯','Chinese',60)
    insert into AllScore(stu_name,category,record)values('毕达哥拉斯','English',95)
    insert into AllScore(stu_name,category,record)values('毕达哥拉斯','Mathmatics',68)
    
    insert into AllScore(stu_name,category,record)values('柏拉图','Chinese',60)
    insert into AllScore(stu_name,category,record)values('柏拉图','English',95)
    insert into AllScore(stu_name,category,record)values('柏拉图','Mathmatics',78)
    
    insert into AllScore(stu_name,category,record)values('亚里士多德','Chinese',40)
    insert into AllScore(stu_name,category,record)values('亚里士多德','English',22)
    insert into AllScore(stu_name,category,record)values('亚里士多德','Mathmatics',25)
    
    insert into AllScore(stu_name,category,record)values('卢梭','Chinese',40)
    insert into AllScore(stu_name,category,record)values('卢梭','English',50)
    insert into AllScore(stu_name,category,record)values('卢梭','Mathmatics',78)
    
    insert into AllScore(stu_name,category,record)values('老庄','Chinese',100)
    insert into AllScore(stu_name,category,record)values('老庄','English',20)
    insert into AllScore(stu_name,category,record)values('老庄','Mathmatics',98)
    
    -----开始行转列-------
    declare @sql nvarchar(4000)
    set @sql='Select stu_name '
    Select @sql=@sql+',sum(case when category='''+category+ ''' then Record else 0 end) As '''+category+''''
    From AllScore Group By category
    set @sql=@sql+' From AllScore Group By stu_name'
    Print @sql
    execute sp_executesql @sql
  • 相关阅读:
    兼容css3.0中的boxshadow
    获取页面和元素可视高度
    关于javascript中apply()和call()方法的区别
    BFC(Block Formatting Context)
    minheight最小高度的实现(兼容IE6、IE7、FF)
    sicily 1825. Nickname
    sicily 2000. Toy Shopping
    sicily 2075. 2.2 Computing the volume of a cylinder
    sicily 2001. Scavenger Hunt
    sicily 1608. Digit Counting
  • 原文地址:https://www.cnblogs.com/HCCZX/p/2855686.html
Copyright © 2020-2023  润新知