Grunden til, at du fik en fejl på din forespørgsel, er, at før underforespørgslen er defineret, skal du angive, hvad du vil vælge fra den. Så hvis du havde præfikset det med select * from
det ville have været en gyldig forespørgsel.
Bemærk, at du ikke behøver at gøre disse or
operationer, da du kan gøre det kortere med en in
operatør.
Du bør også afvise nogle sammenligninger (da du allerede har NOT
). ) og afkort datoer med TRUNC
.
Her er den forespørgsel, jeg vil foreslå:
SELECT TEMP.REG_ID,
TEMP.EVENT_TYPE,
TEMP.EVENT_DATE,
TEMP.PRODUCT_CD,
TEMP.TERM_START_DATE,
CASE WHEN TEMP.EVENT_TYPE IN ('NEW SUBSCRIPTION', 'RENEWAL', 'UPSELL')
AND TEMP.NEXT_EVENT_TYPE = 'CANCELLATION' THEN
LEAST(TEMP.TERM_END_DATE, TEMP.NEXT_TERM_END_DATE)
ELSE TEMP.TERM_END_DATE
END AS TERM_END_DATE,
TEMP.DAYS,
TEMP.AMT
FROM (SELECT REG_ID,
EVENT_TYPE,
EVENT_DATE,
PRODUCT_CD,
TERM_START_DATE,
TERM_END_DATE,
DAYS,
AMT,
LAG(EVENT_TYPE, 1, '-') over (
PARTITION BY REG_ID, PRODUCT_CD
ORDER BY EVENT_DATE, TERM_START_DATE) as PREV_EVENT_TYPE,
LAG(EVENT_DATE, 1) over (
PARTITION BY REG_ID, PRODUCT_CD
ORDER BY EVENT_DATE, TERM_START_DATE) as PREV_EVENT_DATE,
LEAD(EVENT_TYPE, 1, '-') over (
PARTITION BY REG_ID, PRODUCT_CD
ORDER BY EVENT_DATE, TERM_START_DATE) as NEXT_EVENT_TYPE,
LEAD(EVENT_DATE, 1) over (
PARTITION BY REG_ID, PRODUCT_CD
ORDER BY EVENT_DATE, TERM_START_DATE) as NEXT_EVENT_DATE,
LEAD(TERM_END_DATE, 1) over (
PARTITION BY REG_ID, PRODUCT_CD
ORDER BY EVENT_DATE, TERM_START_DATE) as NEXT_TERM_END_DATE
FROM export_table) TEMP
WHERE NOT (TEMP.EVENT_TYPE = 'CANCELLATION'
AND TEMP.PREV_EVENT_TYPE IN ('NEW SUBSCRIPTION', 'RENEWAL', 'UPSELL')
AND TRUNC(TEMP.EVENT_DATE) = TRUNC(TEMP.PREV_EVENT_DATE))
AND NOT (TEMP.NEXT_EVENT_TYPE = 'CANCELLATION'
AND TEMP.EVENT_TYPE IN ('NEW SUBSCRIPTION', 'RENEWAL', 'UPSELL')
AND TRUNC(TEMP.NEXT_EVENT_DATE) = TRUNC(TEMP.EVENT_DATE))
Bemærk, at term_end_date af post 6 er også ændret, da regel 2 er gældende for den.