अगर मैं सही ढंग से समझूं, तो आप प्रत्येक fix_id
. के लिए सबसे हाल की दो पंक्तियों के बीच अंतर चाहते हैं जहां type = 'avg'
।
यदि ऐसा है, तो मैं चर और सशर्त एकत्रीकरण का सुझाव दूंगा:
select fix_id,
max(case when rn = 1 then odds end) as odds,
max(case when rn = 1 then market end) as market,
max(case when rn = 1 then away end) as away,
sum(case when rn = 1 then odds when rn = 2 then - odds end) as diff,
max(type) as type
from (select ao.*,
(@rn := if(@f = fix_id, @rn + 1,
if(@fn := fix_id, 1, 1)
)
) as rn
from (select ao.*
from average_odds ao
where type = 'avg'
order by ao.fix_id, ao.updated desc
) ao cross join
(select @f := -1, @rn := 0) params
) ao
where rn <= 2
group by fix_id;