I am having trouble getting this to work. I am querying the S table to get a list of items and want to join the P table to pull in data for the same date as S + the preceding date, whenever that might have been using the LEAD function.
The issue is the P table is huge and takes forever to query unless a specific date, or small range is given. Since I am joining S & P by a date, the LEAD doesn't seem to work on pulling the prior date's data.
Is there another option? The preceding P.TDATE is often just the prior business date, but can sometimes be over a year ago.
SELECT S.ID,
S.EDATE,
S.PDATE,
S.FACTOR,
S.PTYPE,
P.TDATE,
P.PRICE,
P.PTYPE,
LEAD(P.TDATE) OVER (PARTITION BY P.ID
ORDER BY P.TDATE DESC) AS PRIOR_DATE,
LEAD(P.PRICE) OVER (PARTITION BY P.ID
ORDER BY P.TDATE DESC) AS PRIOR_PRICE,
LEAD(P.PTYPE) OVER (PARTITION BY P.ID
ORDER BY P.TDATE DESC) AS PRIOR_PTYPE
FROM S
LEFT JOIN P ON P.ID = S.ID
AND P.TDATE = S.EDATE
WHERE S.PERIOD = 'D'
AND S.PTYPE IN ('A',
'G',
'Q',
'Y')
ORDER BY S.EDATE ;
I'm getting all the right data, except the prior_date, prior_price and prior_ptype are all blank when they shouldn't be.
There are no NULL values in the date fields.
Is there another efficient way of querying the P table based on the S.EDATE rather than having P.TDATE = S.EDATE in the left join? I believe this condition is the cause for nothing showing up on the "prior" columns due to the LEAD function having no other data to look at.
Thanks,