Answer the question
In order to leave comments, you need to log in
How to fill empty rows with previous value (lag + left join)?
I want to display the weighted average cost of the client's balances, for a month which falls on 1 day.
I form a temporary table with dates for the period:
WITH
DAYS# AS
(
SELECT
LSTDATE
FROM
(
SELECT
:pBegDate + LEVEL - 1 AS LSTDATE
FROM dual
START WITH :pBegDate <= :pEndDate
CONNECT BY :pBegDate + LEVEL - 1 <= :pEndDate
)
)
Answer the question
In order to leave comments, you need to log in
A blank without inline subqueries looks like the code below. There is only one query to the table with data.
But it is necessary to refine it with a file in order to cling to the first account balance that was not included in the reporting period.
(e.g., with a union, paste one line into the lowest subquery)
WITH dt_range AS (
SELECT TRUNC (&dt_start + ROWNUM - 1) dt
FROM DUAL CONNECT BY ROWNUM <= &dt_end - &dt_start + 1
)
,bal AS (
SELECT 101 id_, to_date('20171130', 'yyyymmdd') date_, 50 sum_ FROM DUAL UNION ALL
SELECT 101, to_date('20180102', 'yyyymmdd'), 300 FROM DUAL UNION ALL
SELECT 101, to_date('20180105', 'yyyymmdd'), 500 FROM DUAL UNION ALL
SELECT 101, to_date('20180107', 'yyyymmdd'), 700 FROM DUAL
)
SELECT id_ --MAX(id_) OVER (PARTITION BY grp) id_
,dt
,MAX(sum_) OVER (PARTITION BY grp) sum_
FROM (
SELECT t1.*
,SUM(start_of_group) OVER(ORDER BY t1.dt) grp
FROM (
SELECT bal.id_
,dt_range.dt
,bal.sum_
,CASE WHEN bal.sum_ IS NOT NULL THEN 1 END start_of_group
FROM dt_range
LEFT JOIN bal ON dt_range.dt = bal.date_
) t1
)
ORDER BY dt
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question