日期:2014-05-18  浏览次数:20497 次

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




------解决方案--------------------
SQL code
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 a
order 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


------解决方案--------------------
SQL code


select distinct [time],
(select sum([count]) from tb where [time]<=a.time) 库存
from tb a

/*
time                    库存
----------------------- -----------
2010-01-01 00:00:00.000 1
2010-01-02 00:00:00.000 10
2010-01-03 00:00:00.000 62
2010-01-04 00:00:00.000 62

(4 行受影响)


*/