SQL求助每天实际库存
1表记录每天的货物进出情况
TIME COUNT MONEY
2010-01-01 5 100
2010-01-01 -4 100
2010-01-02 9 100
2010-01-03 10 100
2010-01-03 -8 100
2010-01-03 50 100
2010-01-04 1 100
2010-01-04 -1 100
现在我要求这4天的实际库存怎么写SQL呢
日期 库存
2010-01-01 1
2010-01-02 10
2010-01-03 62
2010-01-04 62
[解决办法]
select time,sum([count]) as [count] into #tmp from tb group by time;select time,[count]=(select sum([count]) from #tmp where time<=a.time)from #tmp as aorder by time;
[解决办法]
declare @tb table (a datetime,count int, moneys money)
insert into @tb select '2010-01-01', 5, 100
union all select '2010-01-01', -4, 100
union all select'2010-01-02', 9, 100
union all select'2010-01-03', 10, 100
union all select'2010-01-03',-8, 100
union all select'2010-01-03', 50 ,100
union all select'2010-01-04', 1, 100
union all select'2010-01-04', -1, 100
select distinct convert(varchar(10),A,120),SUM(count) from @tb
group by a
[解决办法]
select distinct [time],(select sum([count]) from tb where [time]<=a.time) 库存from tb a/*time 库存----------------------- -----------2010-01-01 00:00:00.000 12010-01-02 00:00:00.000 102010-01-03 00:00:00.000 622010-01-04 00:00:00.000 62(4 行受影响)*/