各位大侠: 我一个表,包括
日期 客户号 金额 三个字段,
每日把所有客户的资料采集进去。 现在想设计一个查询, 包括
日期,客户号,余额,比上日余额,比上月底余额 若无上日则比最相近的一个日期余额
若无上月底比如8月30日,则比上月最后一日的余额 请问我应该怎么做。
谢谢大家。100分送上。
日期 客户号 金额 三个字段,
每日把所有客户的资料采集进去。 现在想设计一个查询, 包括
日期,客户号,余额,比上日余额,比上月底余额 若无上日则比最相近的一个日期余额
若无上月底比如8月30日,则比上月最后一日的余额 请问我应该怎么做。
谢谢大家。100分送上。
我想设计一个视图
以便用web查询出来。
--------------------------
可以用 order by
---------- ---------- ----------
02-10月-03 kh01 100
17-10月-03 kh01 200
04-11月-03 kh01 150SQL> select tb.dt,tb.khno,tb.num-(
2 select num from tb tt where tt.dt=(select max(t.dt) from tb t where t.dt<tb.dt
3 and t.khno=tb.khno) and tt.khno=tb.khno) 比上日余额,
4 tb.num-(
5 select num from tb tt where tt.dt=(select max(t.dt) from tb t where t.dt<tb.dt
6 and to_char(tb.dt,'mm')-to_char(t.dt,'mm')=1 and t.khno=tb.khno)
7 and tt.khno=tb.khno) 比上月底余额 from tb;DT KHNO 比上日余额 比上月底余额
---------- ---------- ---------- ------------
02-10月-03 kh01
17-10月-03 kh01 100
04-11月-03 kh01 -50 -50SQL>
create table tb
(rq date,
khh number(10),
jr number(16,2)
)insert into tb values(sysdate - 32,1,1000.5);
insert into tb values(sysdate - 4,1,600.2);
insert into tb values(sysdate,1,1330.5);
insert into tb values(sysdate,2,2200.5);select a.rq,a.khh,a.jr,
a.jr-(select jr from tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and trunc(a.rq) > trunc(c.rq))) 比上日余额,
a.jr-(select jr from tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and months_between(last_day(a.rq),last_day(c.rq)) = 1)) 比上月余额
from tb a where trunc(a.rq) = trunc(sysdate);RQ KHH JR 比上日余额 比上月余额
---------- ---------- ---------- ---------- ----------
11-11月-03 1 1330.5 730.3 330
11-11月-03 2 2200.5
select a.rq,a.khh,a.jr,
a.jr-(select jr from tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and trunc(a.rq) > trunc(c.rq))) 比上日余额,
a.jr-(select jr from tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and months_between(last_day(a.rq),last_day(c.rq)) = 1)) 比上月余额
from tb a;
select 日期,客户号,金额 "余额",金额-lag(金额,1,0) over(partition by 客户号 order by 日期),金额-lag(金额,1,0) over(partition by partition by 客户号 order by decode(sign(last_day(日期)-日期),0,1))
楼主自已测试一下
我分析你们的SQL 觉得应是可以的,
不过在sql plus中运行不行
指向第二个select说缺少表达式,
请问这是什么原因。
为什么不行呢?
试试如下代码,测试表和数据参照我前面的发言
select a.rq,a.khh,a.jr,b.ldjr 比上日余额,c.lmjr 比上月余额 from
tb a,
(select a.khh,a.rq,a.jr - b.jr ldjr from tb a,tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and trunc(a.rq) > trunc(c.rq))) b,
(select a.khh,a.rq,a.jr - b.jr lmjr from tb a,tb b where a.khh = b.khh and b.rq in
(select max(rq) from tb c where a.khh = c.khh and months_between(last_day(a.rq),last_day(c.rq)) = 1)) c
where a.khh = b.khh(+) and a.rq = b.rq(+) and a.khh = c.khh(+) and a.rq = c.rq(+)