如何计算同一列中两个值之间的百分比变化

How to calculate percent change between two values in the same column

我想以特定形式计算同一列中两个值之间的百分比变化,但我不知道我正在尝试做的事情是否可行。

我有一个 table 有 3 个字段

月份、国家、值

order_month country value
2021-01 UK 10
2022-02 UK 20
2021-01 France 20
2022-02 France 18
2021-01 Italy 25
2021-02 Italy 35

我努力得到的东西:

order_month country value
2021-01 UK 10
2022-02 UK 20
diff UK 10
2021-01 France 20
2022-01 France 18
diff France -2
2021-01 Italy 25
2022-02 Italy 35
diff Italy 10

我尝试了很多东西都没有成功。如果你能帮助我,非常感谢。

您需要创建两个子查询或 CTE,将值隔离到您正在分析的月份。

子查询示例

select
  country,
  value as jan_value
from {{table}}
where order_month = '2022-01'

对 2 月执行相同的操作,然后连接表以创建包含县、jan_value 和 feb_value 的新数据集。从这个数据集中,您可以确定值的差异。

您可以为此使用 LEAD/LAG window 函数。我建议使用它为差异创建一个新列,而不是希望在结果中添加一个新行以获得它上面两行的差异。

架构 (MySQL v8.0)

CREATE TABLE data (
  `order_month` date,
  `country` VARCHAR(6),
  `value` INTEGER
);

INSERT INTO data
  (`order_month`, `country`, `value`)
VALUES
  ('2021-01-01', 'UK', '10'),
  ('2022-02-01', 'UK', '20'),
  ('2021-01-01', 'France', '20'),
  ('2022-02-01', 'France', '18'),
  ('2021-01-01', 'Italy', '25'),
  ('2022-02-01', 'Italy', '35');

查询#1

select *,
VALUE - Lead(VALUE) OVER (PARTITION BY COUNTRY ORDER BY ORDER_MONTH DESC) as Month_vs_Month
from data;
order_month country value Month_vs_Month
2022-02-01 France 18 -2
2021-01-01 France 20
2022-02-01 Italy 35 10
2021-01-01 Italy 25
2022-02-01 UK 20 10
2021-01-01 UK 10

View on DB Fiddle

Demo 当然,我正在使用 SQL 服务器,但都支持联合,都支持 FIRST_VALUE 分析,所以...我认为这没问题...

假设:

  • 你的order_month是字符串或者diff就可以了
  • 使用的排序规则支持#'s first 否则排序可能会被关闭。
  • 您可以接受国家/地区排序。

.

WITH CTE AS (SELECT order_month, country, value 
             FROM data 
             UNION ALL
             SELECT Distinct 'diff' order_month, country,
             FIRST_VALUE(value) over (partition by country order by order_month DESC) -
             FIRST_VALUE(value) over (partition by country order by order_month ASC) value
             FROM data) 
SELECT * 
FROM CTE 
ORDER BY country, order_month

给我们:

+-------------+---------+-------+
| order_month | country | value |
+-------------+---------+-------+
| 2021-01-01  | France  |    20 |
| 2022-02-01  | France  |    18 |
| diff        | France  |    -2 |
| 2021-01-01  | Italy   |    25 |
| 2022-02-01  | Italy   |    35 |
| diff        | Italy   |    10 |
| 2021-01-01  | UK      |    10 |
| 2022-02-01  | UK      |    20 |
| diff        | UK      |    10 |
+-------------+---------+-------+

这是做什么的:

  • 使用 first_value 分析生成 CTE,一次按月份升序然后降序排列。
  • 然后我们用旧的减去新的。
  • 然后我们需要对数据进行分组和排序,这样我们就有了 select 来自的 CTE。
  • 我不喜欢用 diff
  • 覆盖 order_month