sqlserver一个动态交叉表的范例
2007-12-11 09:55
351 查看
社区问的人太多了,保存一个备用
--建立测试环境
set nocount on
create table test(model varchar(20),date int ,qty int)
insert into test select 'a','8','10'
insert into test select 'a','10','50'
insert into test select 'b','8','100'
insert into test select 'b','9','200'
insert into test select 'b','10','100'
insert into test select 'c','10','200'
insert into test select 'd','10','300'
insert into test select 'e','11','250'
insert into test select 'e','12','100'
insert into test select 'f','12','150'
go
--测试
declare @sql varchar(8000)
set @sql='select model,'
select @sql=@sql+'sum(case when date='''+cast(date as varchar(10))+''' then qty else 0 end)['+cast(date as varchar(10))+'],'
from (select distinct top 100 percent date
from test order by date)a
set @sql =left(@sql,len(@sql)-1)+' from test group by model'
exec(@sql)
--删除测试环境
drop table test
set nocount off
/**//*
model 8 9 10 11 12
-------------------- ----------- ----------- ----------- ----------- -----------
a 10 0 50 0 0
b 100 200 100 0 0
c 0 0 200 0 0
d 0 0 300 0 0
e 0 0 0 250 100
f 0 0 0 0 150
*/
--建立测试环境
set nocount on
create table test(model varchar(20),date int ,qty int)
insert into test select 'a','8','10'
insert into test select 'a','10','50'
insert into test select 'b','8','100'
insert into test select 'b','9','200'
insert into test select 'b','10','100'
insert into test select 'c','10','200'
insert into test select 'd','10','300'
insert into test select 'e','11','250'
insert into test select 'e','12','100'
insert into test select 'f','12','150'
go
--测试
declare @sql varchar(8000)
set @sql='select model,'
select @sql=@sql+'sum(case when date='''+cast(date as varchar(10))+''' then qty else 0 end)['+cast(date as varchar(10))+'],'
from (select distinct top 100 percent date
from test order by date)a
set @sql =left(@sql,len(@sql)-1)+' from test group by model'
exec(@sql)
--删除测试环境
drop table test
set nocount off
/**//*
model 8 9 10 11 12
-------------------- ----------- ----------- ----------- ----------- -----------
a 10 0 50 0 0
b 100 200 100 0 0
c 0 0 200 0 0
d 0 0 300 0 0
e 0 0 0 250 100
f 0 0 0 0 150
*/
相关文章推荐
- sqlserver一个动态交叉表的范例
- 一个动态交叉报表的例子
- 一个动态交叉分片报表的几种实现方法
- 动态还是静态,这是一个问题
- SQLServer表数据字典/表描述动态查询_改进
- 从别处转的一个sqlite 仿 sqlserver 的类. 没有Demo
- SQLSERVER如何获取一个数据库中的所有表的名称、一个表中所有字段的名称
- [Anonymous] 给一个数组a[2n] ,将前后两段数组元素交叉排列, a1..anb1...bn 变成 a1b1...anbn
- 用c语言做的简易的动态显示直方图和一个有趣的反直觉财富分配实验
- SQLserver 自交叉连接于常用场景
- 一个很好的动态网页设计--电子书
- flume 简单案例 将一个节点的中一个日志文件的动态变化 在 另一个节点的终端输出
- 动态链接库中分配内存引起的问题-- windows已在XX.exe中触发一个断点
- 一个Moss代码搜索范例
- 一个很苯的方法实现TreeView节点的动态添加
- 一个有趣的HTML范例
- Java动态编译一个简单的例子(我转载的,但是经过修定,可以在Eclipse下运行)
- 在SqlServer中把多个job生成一个sql脚本
- C# 调用Excel报 error CS1969: 找不到编译动态表达式所需的一个或多个类型。是否缺少引用?