SQL server 计算同比和环比
在 SQL Server 中,计算同比和环比是常见的数据分析任务。同比是指与去年同期相比的增长率,而环比是指与上一期相比的增长率。以下是如何在 SQL Server 中计算同比和环比的示例。假设我们有一个 Sales 表,其中包含以下字段:
•SaleID:销售记录的唯一标识
•SaleDate:销售日期
•Amount:销售金额
示例表结构
CREATE TABLE Sales (
SaleID INT PRIMARY KEY,
SaleDate DATE,
Amount DECIMAL(18, 2)
);
示例数据
INSERT INTO Sales (SaleID, SaleDate, Amount) VALUES
(1, '2022-10-01', 1000.00),
(2, '2022-10-15', 1500.00),
(3, '2022-11-01', 2000.00),
(4, '2022-11-15', 2500.00),
(5, '2023-10-01', 1200.00),
(6, '2023-10-15', 1800.00),
(7, '2023-11-01', 2200.00),
(8, '2023-11-15', 2700.00);
计算同比和环比
1. 计算同比
假设我们希望计算 2023 年 10 月和 11 月的销售额同比增长率。
WITH CurrentYearSales AS (
SELECT
YEAR(SaleDate) AS Year,
MONTH(SaleDate) AS Month,
SUM(Amount) AS TotalAmount
FROM Sales
WHERE YEAR(SaleDate) = 2023
GROUP BY YEAR(SaleDate), MONTH(SaleDate)
),
LastYearSales AS (
SELECT
YEAR(SaleDate) AS Year,
MONTH(SaleDate) AS Month,
SUM(Amount) AS TotalAmount
FROM Sales
WHERE YEAR(SaleDate) = 2022
GROUP BY YEAR(SaleDate), MONTH(SaleDate)
)
SELECT
c.Year,
c.Month,
c.TotalAmount AS CurrentYearTotal,
l.TotalAmount AS LastYearTotal,
((c.TotalAmount - l.TotalAmount) / l.TotalAmount) * 100 AS YoY_Growth
FROM
CurrentYearSales c
JOIN
LastYearSales l
ON
c.Year - 1 = l.Year AND c.Month = l.Month
ORDER BY
c.Year, c.Month;
2. 计算环比
假设我们希望计算 2023 年每个月的销售额环比增长率。
WITH MonthlySales AS (
SELECT
YEAR(SaleDate) AS Year,
MONTH(SaleDate) AS Month,
SUM(Amount) AS TotalAmount
FROM Sales
WHERE YEAR(SaleDate) = 2023
GROUP BY YEAR(SaleDate), MONTH(SaleDate)
)
SELECT
m.Year,
m.Month,
m.TotalAmount AS CurrentMonthTotal,
LAG(m.TotalAmount) OVER (ORDER BY m.Year, m.Month) AS PreviousMonthTotal,
((m.TotalAmount - LAG(m.TotalAmount) OVER (ORDER BY m.Year, m.Month)) / LAG(m.TotalAmount) OVER (ORDER BY m.Year, m.Month)) * 100 AS MoM_Growth
FROM
MonthlySales m
ORDER BY
m.Year, m.Month;
解释
计算同比
1. CTE(Common Table Expression):
•CurrentYearSales:计算 2023 年每个月的总销售额。
•LastYearSales:计算 2022 年每个月的总销售额。
2. JOIN:
•将 CurrentYearSales 和 LastYearSales 按月份进行连接,确保比较的是相同月份的数据。3. 计算同比增长率:
•使用公式 (CurrentYearTotal - LastYearTotal) / LastYearTotal * 100 计算同比增长率。
计算环比
1. CTE(Common Table Expression):
•MonthlySales:计算 2023 年每个月的总销售额。
2. LAG 函数:
•使用 LAG 函数获取上一个月的销售额。
3. 计算环比增长率:
•使用公式 (CurrentMonthTotal - PreviousMonthTotal) / PreviousMonthTotal * 100 计算环比增长率。
示例输出
同比增长率
Year Month CurrentYearTotal LastYearTotal YoY_Growth
2023 10 3000.00 2500.00 20.00
2023 11 4900.00 4500.00 8.89
环比增长率
Year Month CurrentMonthTotal PreviousMonthTotal MoM_Growth
2023 10 3000.00 NULL NULL
2023 11 4900.00 3000.00 63.33
原文地址:https://blog.csdn.net/qq_36608622/article/details/144057492
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!