Skip to content
Aabha AI Academy
Skip to reading

SQL

09B

Compare these references after your own attempt. You can read them at any time; they do not record a live model or vendor run.

-- 09b: Calculate month over month change
WITH line_totals AS (
 SELECT order_id,SUM(quantity*unit_price-line_discount) AS line_sales
 FROM aabha_sql.order_items GROUP BY order_id
), refund_totals AS (
 SELECT order_id,SUM(amount) AS refunded
 FROM aabha_sql.refunds WHERE refund_date < DATE '2025-04-01' GROUP BY order_id
), order_net AS (
 SELECT o.order_id,o.customer_id,o.order_date,o.channel,
 l.line_sales,COALESCE(r.refunded,0) AS refunded,
 l.line_sales-COALESCE(r.refunded,0) AS net_sales
 FROM aabha_sql.orders AS o
 JOIN line_totals AS l ON l.order_id=o.order_id
 LEFT JOIN refund_totals AS r ON r.order_id=o.order_id
 WHERE o.status='completed' AND o.order_date >= DATE '2025-01-01'
   AND o.order_date < DATE '2025-04-01'
), monthly AS (
 SELECT date_trunc('month',order_date)::date AS month,SUM(net_sales) AS net_sales FROM order_net GROUP BY 1
), compared AS (
 SELECT month,net_sales,LAG(net_sales) OVER (ORDER BY month) AS previous_sales FROM monthly
)
SELECT month::text AS month,net_sales-previous_sales AS absolute_change,
 ROUND(100.0*(net_sales-previous_sales)/NULLIF(previous_sales,0),2) AS percent_change
FROM compared ORDER BY month;

Download this source file