rewrite with cte instead of subselect [code]
- User
rewrite with cte instead of subselect
select (select max(msc.TRADEDATE) as tradedate from SPUR.MICEX_SESSIONS_CALENDAR msc where date_trunc('day', msc.TRADEDATE) <= (unl.DATEUNLOAD)) as tradedate, unl.ID, unl.CREATIONDATE, unl.ID_RULE_UNLOAD, unl.DATEUNLOAD, rmdm.text_code REFERENCE_MDM, rmdm.id id_REFERENCE_MDM from moscow_exchange.unload unl, moscow_exchange.REFERENCE_MDM rmdm where unl.ID_RULE_UNLOAD = rmdm.ID_RULE_UNLOAD ; - Assistant
Certainly! To rewrite the query using a Common Table Expression (CTE), you would structure it like this:
WITH MaxTradeDate AS ( SELECT MAX(msc.TRADEDATE) AS tradedate, date_trunc('day', msc.TRADEDATE) AS truncated_tradedate FROM SPUR.MICEX_SESSIONS_CALENDAR msc GROUP BY truncated_tradedate ) SELECT msc_max.tradedate, unl.ID, unl.CREATIONDATE, unl.ID_RULE_UNLOAD, unl.DATEUNLOAD, rmdm.text_code AS REFERENCE_MDM, rmdm.id AS id_REFERENCE_MDM FROM moscow_exchange.unload unl JOIN moscow_exchange.REFERENCE_MDM rmdm ON unl.ID_RULE_UNLOAD = rmdm.ID_RULE_UNLOAD LEFT JOIN MaxTradeDate msc_max ON date_trunc('day', unl.DATEUNLOAD) = msc_max.truncated_tradedate;In this rewritten version, I've created a CTE named
MaxTradeDatethat calculates the maximumTRADEDATEfor each day by truncating the date to the day level. The main query then uses this CTE to join with theunloadtable to get the requiredtradedate. Note that we perform a left join to match thetruncated_tradedatefrom the CTE with the field in the table (assuming that this is the intended logic based on the subselect). Adjust the join condition as needed to reflect the intended relationship correctly.