mysql动态交叉表_SQL Server数据库动态交叉表的参考示例

SQL Server数据库动态交叉表的参考示例: --建立测试环境set nocount oncreate 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 in

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

*/

本文作者:

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值