We have this query that is running:
SELECT concat_ws(' ', z.ticker,
CASE
WHEN a.date_approved IS NOT NULL THEN TO_CHAR(a.date_approved,'YYMMDD')
WHEN z.date_recommended IS NULL THEN '000000'
ELSE TO_CHAR(z.date_recommended,'YYMMDD')
END,
CASE
WHEN s.ticker IS NOT NULL THEN 6
WHEN a.approved_recommendation IS NOT NULL THEN approved_recommendation
ELSE current_recommendation
END,
REPLACE(CASE
WHEN comments IS NULL THEN 'N/C'
ELSE comments
END,' ','_'))
FROM recommendations z
LEFT JOIN (SELECT ticker FROM scr_tickers) s
ON z.ticker = s.ticker
LEFT JOIN (SELECT ticker, date_approved, approved_recommendation
FROM approved_recommendations) a
ON z.ticker = a.ticker
WHERE z.ticker NOT LIKE 'T.%'
AND z.ticker NOT LIKE 'V.%'
ORDER BY z.ticker;
Now, they want to add another data item after the comments
, which is to retrieve the most recent recommendation value from the recommendations_history
table, where the recommendation value <>current_recommendation
.
In order to do that, I can do a join
, use ROW_NUMBER
with an ORDER BY
and choose the first row. Is that the best way to achieve this in PostgreSQL?
2
Answers
Try this, I introduced a
LEFT JOIN
to incorporate the most recent recommendation from therecommendations_history
table that differs from the current recommendation in the recommendations table. This is achieved by joining a subquery that employs theROW_NUMBER()
window function, partitioned by ticker and ordered by the recommendation date in descending order.case when x is null then y else x end
translates tocoalesce(x,y)
to_char()
function returnsnull
if it getsnull
on inputjoin using
saves you equations and coalescing same-name columns