同比环比增长率计算
SQL数据分析入门SQL
问题
计算每月订单量的环比增长率(与上月对比)和同比增长率(与去年同月对比)。
答题要点
WITH monthly_orders AS (
SELECT
DATE_FORMAT(order_date, '%Y-%m') AS month,
COUNT(*) AS order_count
FROM orders
WHERE status = 'paid'
GROUP BY DATE_FORMAT(order_date, '%Y-%m')
)
SELECT
month,
order_count,
LAG(order_count, 1) OVER (ORDER BY month) AS last_month,
LAG(order_count, 12) OVER (ORDER BY month) AS last_year_month,
ROUND((order_count - LAG(order_count, 1) OVER (ORDER BY month)) * 100.0 /
NULLIF(LAG(order_count, 1) OVER (ORDER BY month), 0), 2) AS mom_growth,
ROUND((order_count - LAG(order_count, 12) OVER (ORDER BY month)) * 100.0 /
NULLIF(LAG(order_count, 12) OVER (ORDER BY month), 0), 2) AS yoy_growth
FROM monthly_orders
ORDER BY month;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题