如何找到每月收入的百分比变化?

时间:2017-03-31 09:47:46

标签: oracle oracle11g

我有一份带有收入和月份的ID样本表,希望每个月都能获得收入的百分比变化。收入从0变为其他东西是无效的。


ID  INCOME  MONTH
1   150     02/2017
1   100     01/2017
2   25      03/2017
2   75      02/2017
2   50      01/2017
3   100     03/2017
3   0       02/2017
4   100     03/2017
4   25      02/2017
4   50      01/2017
5   0       02/2017
5   0       01/2017
6   100     02/2017
6   0       01/2017
6   50      12/2016
7   100     11/2016
7   100     10/2016

%变动=((新收入 - 原始收入)/原始收入)* 100

对于ID#1,对于01 / 2017-02 / 2017,那是((150-100)/ 100)* 100 = 50%。对于ID#2,02 / 2017-03 / 2017,那是((25-75)/ 75)* 100 = -67%,对于01 / 2017-02 / 2017,那是((75-50)/ 50 )* 100 = 50%。

预期结果:


ID  Period              % Change
1   01/2017-02/2017     50
2   01/2017-02/2017     50
2   02/2017-03/2017     -67
4   01/2017-02/2017     -50
4   02/2017-03/2017     300
6   12/2016-01/2017     -100
7   10/2016-11/2016     0

如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

假设您的MONTH列包含DATE数据类型:

SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT t.*,
         LAG( month  ) OVER ( PARTITION BY id ORDER BY month ) AS prev_month,
         LAG( income ) OVER ( PARTITION BY id ORDER BY month ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;

<强>更新

SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT id,
         TO_DATE( month, 'MM/YYYY' ) AS month,
         income,
         LAG( TO_DATE( month, 'MM/YYYY' )  ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_month,
         LAG( income                       ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;