with const as (select 2021 as year1, 2021 as year2, 7 as month1, (month1 + 3) as month2, (month2 + 1) as month3) SELECT description, sku, level2, level3, rev, qty, tren from ( SELECT *, ROW_NUMBER () OVER ( PARTITION BY level2 ORDER BY SUM(revenue) DESC ) rownum, SUM(revenue) OVER (PARTITION BY level2) total, ROUND(SUM(revenue), 2) as rev, SUM(quantity) as qty, tren FROM const, ( select *, cast(past as float) / 3 as past, round( cast(present as float) /(cast(past as float) / 3.0), 2 ) as tren from ( select *, sum(quantity) FILTER ( WHERE year = const.year1 and month between const.month1 and const.month2 ) over (PARTITION BY description) as past, sum(quantity) FILTER ( WHERE year = const.year2 and month = const.month3 ) over (PARTITION BY description) as present from data, const ) ) where year = const.year2 and month = const.month3 GROUP BY description ORDER BY total DESC ) WHERE rownum <= 10 and revenue > 0 order by (sum(revenue) over ( partition by level2 )) desc;