Looping through inner query for each date in outer query
I'm struggling a bit with building a historical dataset to be used in our monthly reporting. The issue is that I have a moderately sized database with some less than 1 million rows of transactional data for commodity valuations or physical positions. Whenever a deal is created or updated, a new line is created with corresponding timestamp. DEALID uniquely identifies a single deal and one DEALID might have several rows if there have been several changes to that specific deal. I would need to build a query to fetch the latest row according to timestamp for each DEALID per last day of each month for whatever period I'm reporting.
SELECT
Cal.MONTHEND
FROM rdv.CALENDAR Cal
INNER JOIN (
SELECT
EOMONTH(dateadd(day,-1,dealsdata.[dv_load_time]) as ASOFDATE,
dealsdata.deal_id,
ROW_NUMBER() OVER( PARTITION BY dealsdata.DEALID ORDER BY dealsdata.[dv_load_time] DESC ) AS dv_load_time_last
FROM [rdv].DEAL_DATA dealsdata ) deals ON deals.ASOFDATE = Cal.MONTHEND and deals.dv_load_time_last = 1
The issue is that deals might not be updated monthly and for some more exotic commodities, not even quarterly. Despite this, I would need a complete list of rows for each month end, even if the latest change took place three months earlier.
Basically what I'm trying to achieve is the WHERE-clause in the inner query below.
SELECT
Cal.MONTHEND
FROM rdv.CALENDAR Cal
INNER JOIN (
SELECT
EOMONTH(dateadd(day,-1,dealsdata.[dv_load_time]) as ASOFDATE,
dealsdata.deal_id,
ROW_NUMBER() OVER( PARTITION BY dealsdata.DEALID ORDER BY dealsdata.[dv_load_time] DESC ) AS dv_load_time_last
FROM [rdv].DEAL_DATA dealsdata
WHERE dealsdata.[dv_load_time] <= Cal.MONTHEND) deals ON deals.ASOFDATE = Cal.MONTHEND AND deals.dv_load_time_last = 1
However, the query above gives me an SQL Error [4104] [S0001]: The multi-part identifier "Cal.MONTHEND" could not be bound. error. I'm a bit stumped here on how to proceed.
Once I get this working I'm going to build a proper static table out of the data so I don't need to be running this query constantly as a view but I would need to be able to do this at least once to establish a complete historical dataset.
EDIT: MONTHEND is a set of dates, e.g. last day of month for every month in 2022.
Posted Feb 28, 2023, 8:25 AM UTC · edited
Replace your
INNER JOINwithCROSS APPLYe g.Thanks! Will try this out when I get back to the office.