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

想得到每日结存,这个SQL如何写
帐期           入帐日期   货物   数量
200707                         A         100     --入帐日期为空表示期初
200707       20070702   A         20       --表示这天的发生数为20,此时结存数应该为120,累加
200707       20070705   A         220     --此时结存数应该为340,累加
...
200707       20070706   B         80
200707       20070709   B         33
200707       20070709   A         22
----------
需要得到的视图像这样
200707                         A         100
200707       20070702   A         120
200707       20070705   A         340
200707       20070709   A         262
...
200707       20070706   B         80
200707       20070709   B         113

这个SQL如何写

------解决方案--------------------
select
帐期,入帐日期,货物
(select sum(数量) from tablename
where 帐期=a.帐期 and 货物=a.货物
and (入帐日期 is null or 入帐日期 <a.入帐日期)
) as 结存
from tablename a
order by 帐期,货物,case when 入帐日期 is null then 0 else 1 end,入帐日期

------解决方案--------------------
--建立测试环境
create table #tb(帐期 int,入帐日期 datetime,货物 varchar(10),数量 int)
insert #tb(帐期,入帐日期,货物,数量)
select '200707 ',NULL, 'A ', '100 ' union all
select '200707 ', '20070702 ', 'A ', '20 ' union all
select '200707 ', '20070705 ', 'A ', '220 ' union all
select '200707 ', '20070706 ', 'B ', '80 ' union all
select '200707 ', '20070709 ', 'B ', '33 ' union all
select '200707 ', '20070709 ', 'A ', '22 '
go
--执行测试语句
select _t.帐期,_t.入帐日期,_t.货物,sum(_t2.数量)
from #tb _t
join #tb _t2 on _t2.帐期 = _t.帐期 and _t2.货物 = _t.货物 and isnull(_t2.入帐日期, '19000101 ') <= isnull(_t.入帐日期, '19000101 ')
group by _t.帐期,_t.入帐日期,_t.货物
order by _t.帐期,_t.货物,_t.入帐日期
go
--删除测试环境
drop table #tb
go
/*--测试结果
帐期 入帐日期 货物
----------- ------------------------------------------------------ ---------- -----------
200707 NULL A 100
200707 2007-07-02 00:00:00.000 A 120
200707 2007-07-05 00:00:00.000 A 340
200707 2007-07-09 00:00:00.000 A 362
200707 2007-07-06 00:00:00.000 B 80
200707 2007-07-09 00:00:00.000 B 113

(6 row(s) affected)
*/

------解决方案--------------------
--建立测试环境

create table #tb(帐期 int,入帐日期 datetime,货物 varchar(10),数量 int)
insert #tb(帐期,入帐日期,货物,数量)
select '200707 ',NULL, 'A ', '100 ' union all
select '200707 ', '20070702 ',