当前位置: 首页 > 图文教程 > 数据库 > MSSQL > SQL Server数据库动态交叉表的参考示例

MSSQL
MD5算法的T-SQL实现(FOR SQL2000)(一)
MD5算法的T-SQL实现(FOR SQL2000)(二)
《高性能的数据库》 第四讲 编程细节(1)
《高性能的数据库》 第四讲 编程细节(2)
MySQL安全性指南 (1)
MySQL安全性指南 (2)
MySQL安全性指南(3)
SQL Server数据库技术(01)
SQL Server数据库技术(02)
SQL Server数据库技术(03)
SQL Server数据库技术(04)
SQL Server数据库技术(05)
SQL Server数据库技术(06)
SQL Server数据库技术(07)
SQL Server数据库技术(08)
SQL Server数据库技术(09)
SQL Server数据库技术(10)
SQL Server数据库技术(11)
SQL Server数据库技术(12)
SQL Server数据库技术(13)

MSSQL 中的 SQL Server数据库动态交叉表的参考示例


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 137 ::
收藏到网摘: n/a

SQL Server数据库动态交叉表的参考示例:

--建立测试环境

以下为引用的内容:

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
*/