sqlserver一个动态交叉表的范例

本文通过创建测试环境并使用动态SQL语句展示如何根据不同日期汇总数据。具体操作包括设置SQL语句来根据特定日期筛选数据并求和,最终实现灵活的数据查询。

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

--建立测试环境
setnocounton
createtabletest(modelvarchar(20),dateint,qtyint)
insertintotestselect'a','8','10'
insertintotestselect'a','10','50'
insertintotestselect'b','8','100'
insertintotestselect'b','9','200'
insertintotestselect'b','10','100'
insertintotestselect'c','10','200'
insertintotestselect'd','10','300'
insertintotestselect'e','11','250'
insertintotestselect'e','12','100'
insertintotestselect'f','12','150'
go
--测试

declare@sqlvarchar(8000)
set@sql='selectmodel,'
select@sql=@sql+'sum(casewhendate='''+cast(dateasvarchar(10))+'''thenqtyelse0end)['+cast(dateasvarchar(10))+'],'
from(selectdistincttop100percentdate
fromtestorderbydate)a

set@sql=left(@sql,len(@sql)-1)+'fromtestgroupbymodel'

exec(@sql)



--删除测试环境
droptabletest
setnocountoff

/**//*
model89101112
---------------------------------------------------------------------------
a1005000
b10020010000
c0020000
d0030000
e000250100
f0000150
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值