商品销售情况统计报表
相关表:
柜台部门表(部门代号,部门名称)
create table dept(dept_code varchar(30),dept_name varchar(60))
insert into dept
select a,a部门
union
select b,b部门
商品类别表(类别代号,类别名称,父类代号)标准的树形结构
create table type(type_code varchar(10),type_names varchar(40),parent_code varchar(10))
insert into type
select 001,电子类,
union
select 00101,电视类,001
union
select 00102,电脑类,001
商品表
create table ware(item_code varchar(20),item_name varchar(60),type_code varchar(10))
insert into ware
select a001,aaa,00101
union
select a002,bbb,001
union
select b001,ccc,00102
销售情况表
create table trans_tab(dt datetime,dept_code varchar(30),item_code varchar(20),qty numeric(18,6))
insert into tras_tab
select 2005-07-01,a,a001,2
union
select 2005-07-02,a,a001,2
union
select 2005-07-01,a,b001,6
union
select 2005-07-01,b,a001,12
union
select 2005-07-01,b,b001,2
union
select 2005-07-02,b,b001,6
根据以上测试数据
要求用一存储过程实现以下功能:
输入参数,销售起止日期(2005-07-01-2005-07-02),部门代号(全部)
输出在销售起止日期期间,指定的部门,所销售各类的商品数量之和,
由于商品类存在包含关系,需统计从大的类到最小的类的各类的数量,每个父类包含该所有子类之和,没有数量的不显示
格式如下:
部门 电子类数量 电视类数量,电脑类
部门a 10 4 6 --10 = 4 + 6
部门b 20 12 8 --20 = 12 + 8
type表的type_code列的值是不是很有规律呢?
我的意思是说, 如果一条记录A的type_code的值是另外一条记录B的type_code值的前缀,
那么记录A一定是记录B的父结点.
如果这样的话,那问题就简单多了.
不需要通过type表的parent_code去繁琐地决定父子关系了.
我倒有一个想法,就是把parent_code值为空的行的parent_code的值补为type_code,这样就可以利用parent_code列来进行sum求和。
--生成测试数据
create table dept(dept_code varchar(30),dept_name varchar(60))
insert into dept select a,a部门
insert into dept select b,b部门
create table type(type_code varchar(10),type_names varchar(40),parent_code varchar(10))
insert into type select 001,电子类,
insert into type select 00101,电视类,001
insert into type select 00102,电脑类,001
create table ware(item_code varchar(20),item_name varchar(60),type_code varchar(10))
insert into ware select a001,aaa,00101
insert into ware select a002,bbb,001
insert into ware select b001,ccc,00102
create table trans_tab(dt datetime,dept_code varchar(30),item_code varchar(20),qty int)
insert into tras_tab select 2005-07-01,a,a001,2
insert into tras_tab select 2005-07-02,a,a001,2
insert into tras_tab select 2005-07-01,a,b001,6
insert into tras_tab select 2005-07-01,b,a001,12
insert into tras_tab select 2005-07-01,b,b001,2
insert into tras_tab select 2005-07-02,b,b001,6
--执行动态查询
declare @s varchar(8000)
set @s =
select
@s = @s+,+type_names+=sum(case when b.type_code like +type_code+% then c.qty else 0 end)
from
type
set @s = select 部门=a.dept_name+@s+ from dept a,ware b,trans_tab c
where
a.dept_code = c.dept_code
and
b.item_code = c.item_code
group by
a.dept_name
exec(@s)
--输出执行结果
部门 电子类 电视类 电脑类
----- ------ ------ ------
部门a 10 4 6
部门b 20 12 8