LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

使用动态SQL语句实现简单的行列转置(动态产生列)

Ccoffee
2015年12月24日 10:4 本文热度 6163
 原始数据如下图所示:(商品的销售明细)

date=业务日期;Item=商品名称;saleqty=销售数量;

-- 建立测试数据(表)
create table test (Date varchar(10), item char(10),saleqty int)
insert test values(''2010-01-01'',''AAA'',8)
insert test values(''2010-01-02'',''AAA'',4)
insert test values(''2010-01-03'',''AAA'',5)
insert test values(''2010-01-01'',''BBB'',1)
insert test values(''2010-01-02'',''CCC'',2)
insert test values(''2010-01-03'',''DDD'',6)

需要实现的报表样式:每一行既每一天,显示所有商品(列)该天的销售数量;

 

 

实现的方法和思路如下:

-- 实现结果的静态SQL语句写法
-- 整理报表需要的格式
select date,
case item when ''AAA'' then saleqty when null then 0 end as AAA,
case item when ''BBB'' then saleqty when null then 0 end as BBB,
case item when ''CCC'' then saleqty when null then 0 end as CCC,
case item when ''DDD'' then saleqty when null then 0 end as DDD
from test

 

 

  

-- 按日期汇总行
select date,
sum(case item when ''AAA'' then saleqty when null then 0 end) as AAA,
sum(case item when ''BBB'' then saleqty when null then 0 end) as BBB,
sum(case item when ''CCC'' then saleqty when null then 0 end) as CCC,
sum(case item when ''DDD'' then saleqty when null then 0 end) as DDD
from test 
group by date

 

 

 

 

-- 处理数据:将空值的栏位填入数字0;
select date,
isnull (sum(case item when ''AAA'' then saleqty end),0) as AAA,
isnull (sum(case item when ''BBB'' then saleqty end),0) as BBB,
isnull (sum(case item when ''CCC'' then saleqty end),0) as CCC,
isnull (sum(case item when ''DDD'' then saleqty end),0) as DDD
from test 
group by date

 

静态SQL语句编写完成!

-- 需要动态实现的SQL部分
isnull (sum(case item when ''AAA'' then saleqty end),0) as AAA,
isnull (sum(case item when ''BBB'' then saleqty end),0) as BBB,
isnull (sum(case item when ''CCC'' then saleqty end),0) as CCC,
isnull (sum(case item when ''DDD'' then saleqty end),0) as DDD

-- 动态语句的实现
select ''isnull (sum(case item when ''''''+item+'''''' then saleqty end),0) as [''+item+'']'' 
from (select distinct item from test) as a
-- 这一步很关键:利用结果集给变量赋值;

-- 完成!
declare @sql varchar(8000)
set @sql = ''select Date''
select @sql = @sql + '',isnull (sum(case item when ''''''+item+'''''' then saleqty end),0) as [''+item+'']'' 
from (select distinct item from test) as a
select @sql = @sql+'' from test group by date''
exec(@sql)

-- 删除测试数据(表)
drop table test


该文章在 2015/12/24 10:11:35 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved