我有一个表,在以这种格式执行每笔交易后存储客户余额:
Client number balance tran_date
7734766688 23000 07-AUG-2014
7734766688 40000 07-AUG-2014
7734766688 20000 10-AUG-2014
7734766688 13000 15-AUG-2014
7734766688 400000 29-AUG-2014
7734766688 200000 02-SEP-2014
客户不希望在8月12日到8月31日之间发表声明,这意味着期初余额为20000
,截止到8月31日的期末余额为400000
如何编写查询以获取如果可用日期仅在最后一次交易中,那么在查询日期和最后日期的余额是什么?
我试过这个以获得期初余额,但它看起来并不充足:
select balance from (select * from client_balances where client_number = '7734766688'
order by TRAN_DATE asc)
where TRAN_DATE >= '01-AUG-2014' and rownum =1;
请帮助,我被卡住了。
答案 0 :(得分:1)
with client_balances as (
select '7734766688' client_number, 23000 balance, to_date('07-08-2014', 'DD-MM-YYYY') tran_date from dual
union all select '7734766688', 40000, to_date('07-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 20000, to_date('10-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 13000, to_date('15-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 400000, to_date('29-08-2014', 'DD-MM-YYYY') from dual
union all select '7734766688', 200000, to_date('02-09-2014', 'DD-MM-YYYY') from dual
),
client_balances_analytic as (
select client_number, balance, tran_date,
lag(balance) over(partition by client_number order by tran_date) prev_balance,
lag(tran_date) over(partition by client_number order by tran_date) prev_tran_date
from client_balances)
select tran_date_start, balance_start, tran_date_end, balance_end from (
select case when tran_date = to_date('12-08-2014', 'DD-MM-YYYY') then tran_date else nvl(prev_tran_date, tran_date) end tran_date_start,
case when tran_date = to_date('12-08-2014', 'DD-MM-YYYY') then balance else nvl(prev_balance, balance) end balance_start,
row_number() over(order by tran_date) rw,
last_value(tran_date) over(order by tran_date rows between current row and unbounded following) tran_date_end,
last_value(balance) over(order by tran_date rows between current row and unbounded following) balance_end
from client_balances_analytic
where client_number = '7734766688' and tran_date between to_date('12-08-2014', 'DD-MM-YYYY') and to_date('31-08-2014', 'DD-MM-YYYY')
) where rw = 1;
滞后函数检索上一行的数据
此查询可能无法正常使用tie(相同的tran_dates)。在这种情况下,您需要一些额外的标准来对事务进行排序(以便最早获得)