set search_path to stoxnet;
select 
x.name, 
x.current_price as current_price, 
x.minp as min_price, 
x.maxp as max_price, 
x.difference as min_max_dif,
(x.current_price - x.minp) / x.current_price as min_cur_dif
from
(
select * from
(
    select 
    name as fname,
    max(id) as maxid
    from quote
    group by name
) as q_id
left join
(
    select 
    id, 
    last_price as current_price 
    from quote
) as q_currentprice
on q_id.maxid = q_currentprice.id
left join
(
    select 
        name, 
        min(last_price) as minp, 
        max(last_price) as maxp, 
        (min(last_price) - max(last_price)) / max(last_price) as difference 
    from quote q1
    group by name 
) as q_minmax
on q_id.fname = q_minmax.name
) as x order by min_cur_dif desc;

