zoukankan      html  css  js  c++  java
  • SQLServer 使用变量动态行转列

    drop table #test
    create table #test
    (
        id int identity(1,1) primary key,
        bizDate varchar(50),
        type varchar(50),
        qty float
    )

    insert into #test
    select '20110501','A',20.5 union all
    select '20110501','B',98 union all
    select '20110501','C',100.5 union all
    select '20110501','A',32 union all
    select '20110501','C',76.8 union all
    select '20110502','B',58 union all
    select '20110502','A',111 union all
    select '20110502','A',51 union all
    select '20110502','A',85 union all
    select '20110502','B',52 union all
    select '20110502','C',43 union all
    select '20110503','A',158 union all
    select '20110503','C',58 union all
    select '20110503','B',28 union all
    select '20110503','B',65 union all
    select '20110503','A',11 union all
    select '20110503','A',25 union all
    select '20110503','C',63

    declare @sql varchar(8000)
    set @sql = 'select type' 
    select @sql = @sql + ' , SUM(CASE WHEN bizDate=''' + bizDate + ''' then qty else 0 end) [' + bizDate + ']'
    from (select distinct bizDate from #test) as a order by bizDate--此行的SQL用于找出不重复的日期,也就是结果集中所有的日期
    set @sql = @sql + ' from #test A group by type'
    print @sql
    exec(@sql)


    --打印出来的完整SQL是:
    select type ,
           SUM(CASE WHEN bizDate='20110501' then qty else 0 end) [20110501] ,
           SUM(CASE WHEN bizDate='20110502' then qty else 0 end) [20110502] ,
           SUM(CASE WHEN bizDate='20110503' then qty else 0 end) [20110503]
           from #test A group by type


          

    /*
    PS. SQLServer里的中括号作用:
     若表名、字段名、列名等与数据库里的关键字有冲突,则可以给该表名或字段名加上"[]"以识区别。
     上面的例子中是以日期作为列名,也可用"[]"标识
    */

  • 相关阅读:
    备忘: Visual Studio 2013 VC++ IDE 使用小贴示。
    获取动态数组指针 所指向数组长度的一种方法
    备忘:C++ 类 (初学之实录)。
    备忘:VC++ 中的异常处理
    备忘: C++中的 vector 容器
    备忘:C++基础 -- 数据类型的学习总结
    Windws Server 2008 R2 WEB环境配置之MYSQL 5.6.22安装配置
    Windows Server 2008 R2 WEB服务器配置系列文章索引
    php学习过程二
    php学习过程一
  • 原文地址:https://www.cnblogs.com/xcxcxcxc/p/5541199.html
Copyright © 2011-2022 走看看