sqlserver一个动态交叉表的范例_SQL SERVER数据库_黑客防线网安服务器维护基地--Powered by WWW.RONGSEN.COM.CN

sqlserver一个动态交叉表的范例

作者:黑客防线网安SQL维护基地 来源:黑客防线网安SQL维护基地 浏览次数:0

本篇关键词:范例交叉动态一个
黑客防线网安网讯:  社区问的人太多了,保存一个备用  --建立测试环境set nocount oncreate table test(model varchar(20),date int ,qty int)insert into test select 'a','8','10&...

  社区问的人太多了保存一个备用

  --建立测试环境

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

    黑客防线网安服务器维护方案本篇连接:http://www.rongsen.com.cn/show-9757-1.html
网站维护教程更新时间:2012-03-21 02:24:41  【打印此页】  【关闭
我要申请本站N点 | 黑客防线官网 |  
专业服务器维护及网站维护手工安全搭建环境,网站安全加固服务。黑客防线网安服务器维护基地招商进行中!QQ:29769479

footer  footer  footer  footer