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

如何检验最后一笔记录的余额值是否正确?
费用明细表:tbl_person_list

Lid Pid Lmoney Pmoney LDate
---------------------------------------
1   1   50     50  2008-2-11
2   2   50     50  2008-2-11
3   3   50     50  2008-2-11
4   1   50     100 2008-2-13
5   2   -56     -6  2008-2-13
6   3   100     150  2008-2-13
7   1   100     200  2008-2-14
8   3   150     300  2008-2-14



现在想写一个余额检验语句,即检查每个人的费用总和值(sum(Lmoney))是否与其最后一笔记录的余额值(Pmoney)相等
把不相等的人员信息(PID)列出来


如果有办法知道是从什么时间开始出现不相等的情况更好。

------解决方案--------------------
我试着写了一下,看执行结果是对了,不知道会不会隐含着什么BUG,现发出来,大家看看。
//解决每个Pid最小日期的错误
select *
from (select b.*
from (select pid,min(ldate) as ldate from test group by pid) a,test b
where a.pid=b.pid and a.ldate = b.ldate ) c
where c.Lmoney <> c.pmoney
union all
//解决比最小日期大的错误
select c.* from
(select distinct a.* from test a,test b where a.pid = b.pid and a.ldate > b.ldate) c
inner join 
(select pid,sum(Lmoney) as m from test group by pid) d
on c.pid = d.pid
and c.pmoney <>d.m