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

最新文章

  1. 【技巧】为ComboBox添加自动提示
  2. CircularSeekBar
  3. 对于家政020 APP平台如何走出资本寒冬?
  4. 编写自己的Acunetix WVS漏洞扫描脚本详细教程
  5. mysql指定某行或者某列的排序
  6. Android View.onMeasure方法的理解(转载)
  7. CSRF——攻击与防御
  8. vim的用法
  9. [转载] 编程每一天(Write Code Every Day)
  10. [转载] Redis之七种武器
  11. Android远程桌面助手(Build 0737)
  12. μC/OS-II 信号量集
  13. (网页)angularJs中怎么模拟jQuery中的this?(转)
  14. 手工命令行 搭建 hadoop 和 spark 环境
  15. vm参数配置的理解
  16. 关于LVS+Nginx为什么会被同时使用的思考
  17. VS2010 SP1安装失败之”此计算机的状态不支持此安装“()
  18. BZOJ 3751: [NOIP2014]解方程 数学
  19. 网页上播放音频、视频Mp3,Mp4
  20. python bottle学习(四)request.quest/query_string/params/body等方法介绍

热门文章

  1. c#用控制台程序安装启动停止卸载服务
  2. Codeforces Round #467 Div.2题解
  3. Oracle存储过程及函数的练习题
  4. jQuery练习:表单模态框
  5. java 常见问题
  6. 简单的SpringBoot环境搭建
  7. 【POJ 1981】Circle and Points(已知圆上两点求圆心坐标)
  8. Oracle学习总结(5)—— SQL语句经典案例
  9. linux -- 视频尺寸-cif、2cif、dcif、D1、HD1、4D1
  10. round()和trunc()函数的应用