已知:当前时间(截取yyyy-mm) 目标1:查询进销存表当中距离当前时间连续3个月内进货数量=0的产品名称;

---------------------------------------------------------------

1.

select a.产品名称 from产品名称表 a,
(select产品ID,sum(进货数量) as 进货数量
from 进销存表
where时间 >= dateadd (mm,-3,getdate()) and时间 <= getdate()
group by产品ID) b
where b.进货数量 = 0 and a.产品ID = b.产品ID;

2.

用触发器实现。

BTW:用中文描述字段太累了。

---------------------------------------------------------------

问题二:
建议把字段“库存数量”从“进销存表”移动到“产品名称表”
修改后,新表结构如下:

产品名称表结构:产品ID,产品名称,库存数量
进销存表结构:产品ID,进货数量,销售数量,时间(yyyy-mm)

对insert,delete,update分别写三个触发器:

create procedure on 进销存表 as tri_test1
on insert

select 产品ID,绝对入库数量=sum(进货数量-销售数量) into #tmp
from inserted
group by 产品ID

update 产品名称表
set 库存数量=库存数量+#tmp.绝对入库数量
from 产品名称表,#tmp
where 产品名称表.产品ID=#tmp.产品ID

create procedure on 进销存表 as tri_test2
on delete

select 产品ID,绝对入库数量=sum(进货数量-销售数量) into #tmp
from deleted
group by 产品ID

update 产品名称表
set 库存数量=库存数量-#tmp.绝对入库数量
from 产品名称表,#tmp
where 产品名称表.产品ID=#tmp.产品ID

create procedure on 进销存表 as tri_test3
on update

select 产品ID,绝对入库数量=sum((inserted.进货数量-inserted.销售数量)-(deleted.进货数量-deleted.销售数量)) into #tmp
from deleted,inserted
where deleted.产品ID=inserted.产品ID
group by 产品ID

update 产品名称表
set 库存数量=库存数量-#tmp.绝对入库数量
from 产品名称表,#tmp
where 产品名称表.产品ID=#tmp.产品ID

改了你的表结构,不知是不是我对你的表设计理解有误。
总之,就是个思想,我的程序不能满足你的需要的话,你顺着这个思路改就行了。

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus