select x.id,x.sum-y.sum margin from 
(
    select a.id,a.sum from t_table a,
    (
        select id,max(time) time from t_table group by id 
    ) b
    where a.id=b.id and a.time=b.time
) x,
(
    select a.id,a.sum from t_table a,
    (
        select id,min(time) time from t_table group by id
    ) b
    where a.id=b.id and a.time=b.time
) y
where x.id=y.id;