クライアントがこの形式で行うすべてのトランザクションの後に、クライアントの残高を格納するテーブルがあります。
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;
助けてください、立ち往生しています。
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;
ラグ関数は前の行からデータを取得します
このクエリは、タイ(同じtran_dates)では正しく機能しない可能性があります。この場合、トランザクションを並べ替えるためにいくつかの追加の基準が必要です(最も早く取得するため)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加