I’m creating a filter for Brazilian REITs, my goal is to get the last recorded price for each REIT and use it as a source for some calculations.
My goal (with a single price record for each REIT):
Actual result: (2 price records for VISC and one for GARE):
my actual query:
select
r.ticker,
rp.price,
SUM(rq.amount) as quota_amount,
SUM(rq.amount * rq.price) / SUM(rq.amount) as average_price,
CONCAT(ROUND((rp.price - AVG(rq.price)) / rp.price * 100, 2), '%') as variation_percentage,
SUM(rq.amount) * rp.price as balance,
SUM(rq.amount * rq.price) as total_invested,
(SUM(rq.amount) * rp.price) - (SUM(rq.amount * rq.price)) as currency_variation,
rp.registered_at as price_registration_date
from
reit_quote rq
inner join reit r on
r.id = rq.reit_id
inner join reit_price rp on
rq.reit_id = rp.reit_id
group by
r.ticker,
rp.price,
rp.registered_at
order by rp.registered_at desc
DATABASE: postgres