表中有记录如下:
产品名称 进 出
A 20 0
B 30 0
A 0 15
B 15 0
A 0 5
A 5 0
A 1 0
查询数据时:
得出库存SUM(进-出)为 6但我要得到的数据是
(20-15-5)=0之后的两条数据
A 5 0
A 1 0
因为数据量很大,我要每次得到的都是(前面和为0)之后的库存的记录??
...全文
5218打赏收藏
问一个问题
表中有记录如下: 产品名称 进 出 A 20 0 B 30 0 A 0 15 B 15 0 A 0 5 A 5 0 A 1 0 查询数据时: 得出库存SUM(进-出)为 6但我要得到的数据是 (20-15-5)=0之后的两条数据 A 5 0 A 1 0 因为数据量很大,我要每次得到的都是(前面和为0)之后的库存的记录??
select x.* from 表 x inner join
(
select max(id) as id, 产品名称 from 表 t
where (select sum(进)-sum(出) from 表 where id<=t.id and 产品名称=t.产品名称) = 0
group by all 产品名称
) y on x.产品名称 = y.产品名称 and x.id > isnull(y.id, 0)
order by x.id
--定义表结构(用表变量的方法,@tb相当于一个表)
declare @tb table(产品名称 varchar(10),进 int,出 int,日期 datetime)
--插入数据到表中
insert into @tb
select 'A',20,0,'2003-10-2 08:30'
union all select 'B',30,0,'2003-10-2'
union all select 'A',0,15,'2003-10-3 08:20'
union all select 'B',15,0,'2003-10-3'
union all select 'A',0,5,'2003-10-3 09:30'
union all select 'A',5,0,'2003-10-3 09:50'
union all select 'A',1,0,'2003-10-4 10:20'
--从表中查询出数据,用了嵌套子查询的方法
select *
,结余=(select sum(进-出) from @tb where 产品名称=a.产品名称 and 日期<=a.日期)
from @tb a
如果日期字段不重复,可以用下面的方法,否则用大力的方法
declare @tb table(产品名称 varchar(10),进 int,出 int,日期 datetime)
insert into @tb
select 'A',20,0,'2003-10-2 08:30'
union all select 'B',30,0,'2003-10-2'
union all select 'A',0,15,'2003-10-3 08:20'
union all select 'B',15,0,'2003-10-3'
union all select 'A',0,5,'2003-10-3 09:30'
union all select 'A',5,0,'2003-10-3 09:50'
union all select 'A',1,0,'2003-10-4 10:20'
select *
,结余=(select sum(进-出) from @tb where 产品名称=a.产品名称 and 日期<=a.日期)
from @tb a
可以解释一下吗??
declare @tb table(产品名称 varchar(10),进 int,出 int,日期 datetime)
insert into @tb
select 'A',20,0,'2003-10-2 08:30'
union all select 'B',30,0,'2003-10-2'
union all select 'A',0,15,'2003-10-3 08:20'
union all select 'B',15,0,'2003-10-3'
union all select 'A',0,5,'2003-10-3 09:30'
union all select 'A',5,0,'2003-10-3 09:50'
union all select 'A',1,0,'2003-10-4 10:20'
select *
,结余=(select sum(进-出) from @tb where 产品名称=a.产品名称 and 日期<=a.日期)
from @tb a
--如果日期字段不重复,可以用下面的方法,否则用大力的方法
declare @tb table(产品名称 varchar(10),进 int,出 int,日期 datetime)
insert into @tb
select 'A',20,0,'2003-10-2 08:30'
union all select 'B',30,0,'2003-10-2'
union all select 'A',0,15,'2003-10-3 08:20'
union all select 'B',15,0,'2003-10-3'
union all select 'A',0,5,'2003-10-3 09:30'
union all select 'A',5,0,'2003-10-3 09:50'
union all select 'A',1,0,'2003-10-4 10:20'
select *
,结余=(select sum(进-出) from @tb where 产品名称=a.产品名称 and 日期<=a.日期)
from @tb a
select x.* from 表 x inner join
(
select max(日期) as 日期, 产品名称 from 表 t
where (select sum(进)-sum(出) from 表 where 日期<=t.日期 and 产品名称=t.产品名称) = 0
group by all 产品名称
) y on x.产品名称 = y.产品名称 and datediff(d, x.日期, isnull(y.日期, 0)) < 0
order by x.日期
各位大侠,我忘记了说的事还有一个时间字段,就是说每插入一条新记录的时间都是增加的.
这样好做吗??
产品名称 进 出 日期
A 20 0 2003-10-2
B 30 0 2003-10-2
A 0 15 2003-10-3
B 15 0 ......
A 0 5 .......
A 5 0 2003-10-3
A 1 0 2003-10-4