Uw raamclausule kijkt naar last_effective_dates
over al uw gegevens. U moet een partition by
clausule om het te beperken tot de huidige klant:
OVER (PARTITION BY nm.CUSTOMER_ID
ORDER BY nm.LATEST_EFFECTIVE_DATE
RANGE BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING)
Dus:
SELECT NM.CUSTOMER_ID customer_id,
NM.LATEST_EFFECTIVE_DATE start_date,
NVL (
CASE
WHEN nm.LATEST_EFFECTIVE_DATE IS NULL
THEN
TO_DATE ('12/12/9999', 'dd/mm/yyyy')
ELSE
FIRST_VALUE (
nm.LATEST_EFFECTIVE_DATE)
OVER (PARTITION BY nm.CUSTOMER_ID
ORDER BY nm.LATEST_EFFECTIVE_DATE
RANGE BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING)
END,
TO_DATE ('12/12/9999', 'dd/mm/yyyy'))
end_date,
NM.PRESENT_QUANTITY PRESENT_quantity
FROM nm_cust_appliance_history nm
WHERE NM.APPLIANCE_INFO_ID = 10484
ORDER BY customer_id, start_date;
Als u het ooit voor meer dan één appliance_info_id
dan moet je dat toevoegen aan de partition by clause
ook.
Een dummy extra record gebruiken om te simuleren wat je ziet, geleverd via een CTE:
with nm_cust_appliance_history(appliance_info_id, customer_id, latest_effective_date, present_quantity) as (
select 10484, 96, date '2009-12-20', 10 from dual
union all select 10484, 96, date '2014-11-18', 12 from dual
union all select 10484, 96, date '2015-11-26', 14 from dual
union all select 10484, 42, date '2009-12-21', 15 from dual
)
uw oorspronkelijke zoekopdracht krijgt:
CUSTOMER_ID START_DATE END_DATE PRESENT_QUANTITY
----------- ---------- ---------- ----------------
42 2009-12-21 2014-11-18 15
96 2009-12-20 2009-12-21 10
96 2014-11-18 2015-11-26 12
96 2015-11-26 9999-12-12 14
en de partitie-by-query hierboven krijgt:
CUSTOMER_ID START_DATE END_DATE PRESENT_QUANTITY
----------- ---------- ---------- ----------------
42 2009-12-21 9999-12-12 15
96 2009-12-20 2014-11-18 10
96 2014-11-18 2015-11-26 12
96 2015-11-26 9999-12-12 14