Joining to bodymass table by time
Data in the bodymass table can be transformed as (for account 1):
select kilos, time as start, (case when lead(time) over (order by time asc) is null then 'infinity'::timestamptz else lead(time) over (order by time asc) end) as end from bodymass where account=1;
Thereby giving a table with clear timespans. Joining can then be performed by a nested table:
with bm_report as (
select kilos, time as start,
(case when lead(time) over (order by time asc) is null
then 'infinity'::timestamptz
else lead(time) over (order by time asc) end) as end from bodymass
where account=1)
select
t.time, t.exercise, t.kilos, b.kilos as bodymass, round(100*t.kilos/b.kilos, 1) as ratio
from training t
inner join bm_report b on t.time >= b.start and t.time < b.end
where t.account=1 and exercise=1
order by 1;