Oracle
 sql >> Database >  >> RDS >> Oracle

Sbagliare la data successiva da una colonna della data per tutti i clienti Oracle

La tua clausola finestra sta guardando last_effective_dates su tutti i tuoi dati. Devi aggiungere una partition by clausola per restringerla al cliente attuale:

  OVER (PARTITION BY nm.CUSTOMER_ID
        ORDER BY nm.LATEST_EFFECTIVE_DATE
        RANGE BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING)

Quindi:

  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;

Se hai bisogno di eseguirlo per più di un appliance_info_id quindi dovrai aggiungerlo alla partition by clause anche.

Utilizzo di un record aggiuntivo fittizio per simulare ciò che stai vedendo, fornito tramite un 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
)

la tua query originale ottiene:

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

e la query partizione per sopra ottiene:

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