一个查当前月库存的算法及详解
现在做一个关于库存方面的系统,涉及到查每个月的库存。看来这是一个很简单的问题,但是这里涉及到我要查前面任何一个月的最后库存,我并不一定要查当前月的库存,如果是查当前月的库存,就把现在所有有效的库存记录显示出来就可以了(注:我的库存表是如果有入库数量,对应的原来的记录就设为无效,插入一条总和的记录并设为有效)。
如现在的时间是九月,我要看八月或者是七月甚至是更前面每一种东西的在那个时候的库存,这里就假设为要看八月的吧,但是八月有一种编号为A的物品在七月没有进出库,也就是这个A在八月的库存,其实是七月的库存,有的甚至有几个月都没有进出库的,那就要一直取到与要查看月最接近的那个月的库存作为需要的库存。
我的算法是如下:
如果当前月存在,就直接显示,如果不存在就一直往前面推,直到一直推到数据库第一条记录的日期为止,如果都还同有找到,那就说明不存在该货物的记录,如下图:
![](https://p-blog.csdn.net/images/p_blog_csdn_net/fenglibing/4c584fb238de41c6b59e5fed6700e2c2.gif)
相关算法,JAVA源程序如下:
/******************
定义变量
**********************/
private
int
smallestBeginYear;
private
int
smalleatBeginMonth;
private
int
currentYear_;
private
int
currentMonth_;
private
DBMS_Conn conn=
new
DBMS_Conn();
/**
*
取得指定月结存
*
@param
monthType
0
表示查看上一个月,
1
表示这个月
*
@param
currentMonth
当前月
*
@param
componentID
元件号
*
@return
*/
public
int
getNumInWareHouseBySpecialMonth(
int
monthType,
int
currentYear,
int
currentMonth,
int
componentID) {
if
(monthType==0) {
currentMonth--;
}
currentYear_=currentYear;
currentMonth_=currentMonth;
int
num=0;
boolean
doOK=
false
;
boolean
again=
false
;
while
(!doOK)
//
循环,直到条件不满足为止
{
String sql=
"SELECT top 1 nowLeft from ku_in_out where "
;
sql+=
" deletedOrNot=0 and month(cdate(InOrOutTime))="
+currentMonth_;
sql+=
" and year(cdate(InOrOutTime))="
+currentYear_;
sql+=
" and componentID="
+componentID+
" order by InOrOutTime desc,ID DESC"
;
ResultSet rs;
try
{
rs=conn.executeSQLReturnResult(sql);
if
(rs.next()) {
num=rs.getInt(1);
doOK=
true
;
}
else
{
//
如果当前月没有记录,就查看前面几个月的是否有该记录
if
(!getAProperMonthAndYear(currentYear_,currentMonth_,smallestBeginYear,smalleatBeginMonth)) {
doOK=
true
;
}
else
{
again=
true
;
}
}
}
catch
(SQLException e) {
e.printStackTrace();
}
}
return
num;
}
/**
*
用该方法取得一个合适的年、月,因为有的记录可能上个月没有操作(如八月,现在九月,
*
但七月就记录),相当于现在的库存记录就是七月的
*
@param
currentYear
*
@param
currentMonth
*
@param
samllestYear
*
@param
smallestMonth
*
@return
*/
private
boolean
getAProperMonthAndYear(
int
currentYear,
int
currentMonth,
int
samllestYear,
int
smallestMonth) {
boolean
ok=
false
;
//
用以确认是否取前面一个月操作
OK
int
testI=0;
if
(currentMonth>1) {
if
(currentYear>samllestYear)
{
currentMonth--;
ok=
true
;
}
else
if
(currentYear==samllestYear && currentMonth>smallestMonth) {
currentMonth--;
ok=
true
;
}
}
else
{
if
(currentYear>samllestYear)
{
currentYear--;
currentMonth=12;
ok=
true
;
}
}
if
(ok) {
currentYear_=currentYear;
currentMonth_=currentMonth;
}
return
ok;
}