zoukankan      html  css  js  c++  java
  • 典型的列变行,用动态语句来做

    --测试数据

    declare @tab table(id varchar(3),class varchar(10),sums int)

    insert @tab
    select '001','计算机','65' union all

    select '002','计算机','75' union all
    select '001','美术','77' union all

    select '003','体育','54' union all
    select '004','美术','65' union all

    select '005','体育','55' union all
    select '001','体育','56' union all

    select '002','体育','88' union all
    select '002','美术','98' union all

    select '003','计算机','82' union all
    select '003','美术','92' union all

    select '004','计算机','85' union all
    select '004','体育','25' union all

    select '005','计算机','89' union all
    select '005','美术','99';


    --select * from @tab

    --下面是测试代码


    select * into #temp1 from @tab
    declare @str varchar(8000)

    set @str='select id as 编号,'
    select @str=@str+'

    sum(case class when'''+class+'''then sums else 0 end) as'''+class+'成绩'+''','

    from (select distinct class from #temp1)t

    set @str=left(@str,len(@str)-1)+' from #temp1 group by id'
    exec(@str)

    drop table #temp1


    /* 下面是测试结果

    (所影响的行数为 15 行)



    (所影响的行数为 15 行)

    编号 计算机成绩 美术成绩 体育成绩 

    ---- ----------- ----------- ----------- 
    001 65 77 56
    002 75 98 88

    003 82 92 54
    004 85 65 25
    005 89 99 55 */

  • 相关阅读:
    Java中的集合类
    Java中的包装类
    Java中的多线程总结(转)
    Java开发中的23种设计模式详解 (转)
    Java中异常处理和设计
    Jmeter的ForEach控制器
    Jmeter事务控制器
    Jmeter下线程顺序启动
    Jmeter跨线程调用参数
    Jmeter使用Python
  • 原文地址:https://www.cnblogs.com/zxktxj/p/2575187.html
Copyright © 2011-2022 走看看