LAG/LEAD同环比计算
SQL查询入门SQL
问题
计算每月销售额、环比增长率和同比增长率。
答题要点
WITH monthly_sales AS (
SELECT
DATE_FORMAT(order_date, '%Y-%m') AS month,
YEAR(order_date) AS year,
MONTH(order_date) AS month_num,
SUM(amount) AS sales
FROM sales
GROUP BY DATE_FORMAT(order_date, '%Y-%m'), YEAR(order_date), MONTH(order_date)
)
SELECT
month,
sales,
LAG(sales, 1) OVER (ORDER BY month) AS prev_month_sales,
ROUND((sales - LAG(sales, 1) OVER (ORDER BY month)) * 100.0
/ LAG(sales, 1) OVER (ORDER BY month), 2) AS mom_growth,
LAG(sales, 12) OVER (ORDER BY month) AS prev_year_sales,
ROUND((sales - LAG(sales, 12) OVER (ORDER BY month)) * 100.0
/ LAG(sales, 12) OVER (ORDER BY month), 2) AS yoy_growth
FROM monthly_sales
ORDER BY month;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题