Sql实现递减查询
时间:2011-05-11 来源:沉默的人
显示开发中经常碰到这样的问题
采购某项物品,但是是分批入库的,这时候有可能需要查询该项物品的入库情况列表
比如 物品 采购量 已入库量 剩余入库量 入库时间 。。。
A 100 10 90 2011-05-09
A 100 20 70 2011-05-10
A 100 50 20 2011-05-11
A 100 20 0 2011-05-12
实现如下:
Create Table Sam_Product
(
UID int Identity(1,1) Primary Key,
ProdName NVarchar(100),
UsedQty int,
Remark NVarchar(100)
)
Create Table Sam_StockIn
(
UID int Identity(1,1) Primary Key,
UnitID int Foreign Key References Sam_Product(UID),
StockedIn int,
StockDate DateTime,
Remark NVarchar(100)
)
Insert Into Sam_Product(ProdName,UsedQty,Remark)
Select 'jianpan' , 5,''
Insert into Sam_StockIn(UnitID,StockedIn,Stockate)
Select 1,1,'2011-05-09'
Union
Select 1,2,'2011-05-10'
Union
Select 1,2,'2011-05-11'
查询语句
Select a.UID,ProdName,UsedQty,StockedIn,
a.UsedQty - (Select Sum(StockedIn) From Sam_StockIn where UnitID = b.UnitID and StockDate <= b.StockDate) as AliveQty,
StockDate From Sam_Product a inner join Sam_StockIn b on a.UID=b.UnitID
PS:对于复杂查询的话,这样的语句效率是很低的,但是至少能实现,呵呵