WITH yearly_sales AS ( SELECT SUM(sales) AS total_sales, yr FROM ( SELECT sales, EXTRACT(YEAR FROM order_date) AS yr FROM stores_ma ) a GROUP BY yr ) SELECT cur_year.yr, (cur_year.total_sales - prev_year.total_sales) AS diff FROM yearly_sales AS cur_year LEFT JOIN yearly_sales AS prev_year ON prev_year.yr = cur_year.yr - 1 ORDER BY cur_year.yr ASC;
WITH yearly_sales AS ( SELECT SUM(sales) AS total_sales, yr FROM ( SELECT sales, EXTRACT(YEAR FROM order_date) AS yr FROM stores_ma ) a GROUP BY yr ) SELECT cur_year.yr, (cur_year.total_sales - prev_year.total_sales) AS diff FROM yearly_sales AS cur_year LEFT JOIN yearly_sales AS prev_year ON prev_year.yr = cur_year.yr - 1 ORDER BY cur_year.yr ASC;
with yr_sales as ( select extract(YEAR from order_date) as yr, sum(sales) total_sales from stores_ma group by 1 order by yr ) select yr, total_sales, total_sales - lag(total_sales) over (order by yr) as diff, round( 100 * (total_sales - lag(total_sales) over (order by yr)) / lag(total_sales) over (order by yr) , 2) as pct from yr_sales a;