逐月增长百分比 - MySQL 5.x

Percentage growth month by month - MySQL 5.x

我有一个 table sales 和一些 columnsdata 像这样:

SELECT order_date, sale FROM sales;

+------------+------+
| order_date | sale |
+------------+------+
| 2020-01-01 |   20 |
| 2020-01-02 |   25 |
| 2020-01-03 |   15 |
| 2020-01-04 |   30 |
| 2020-02-05 |   20 |
| 2020-02-10 |   20 |
| 2020-02-06 |   25 |
| 2020-03-07 |   15 |
| 2020-03-08 |   30 |
| 2020-03-09 |   20 |
| 2020-03-10 |   40 |
| 2020-04-01 |   20 |
| 2020-04-02 |   25 |
| 2020-04-03 |   10 |
+------------+------+

我想计算,例如,monthly growth rate

根据前面的数据示例,预期结果如下:

month  sale  growth_rate  

     1    90            0         
     2    65       -27.78          
     3   105        61.54         
     4    55       -47.62      

我们有一个旧的 MySQL version, 5.x.

任何人都可以帮助我或给我一些线索来实现这个目标吗?

您可以使用聚合和 window 函数。像他的东西:

select year(order_date) as year, month(order_date) as month, sum(sale) as sale,
       100 * (1 - sum(sale) / lag(sum(sale), 1, sum(sale)) over (order by min(order_date)) as growth_rate
from t
group by year, month

有点复杂:

select 
   s.*
   -- calculate rate
   , ifnull(round((s.mnt_sale - n.mnt_sale)/n.mnt_sale * 10000)/100, 0) as growth_rate
from ( 
    -- calculate monthly summary
    select month(order_date) mnt, sum(sale) mnt_sale
    from sales
    group by mnt
) s
left join ( -- join next month summary
    -- calculate monthly summary one more time
    select month(order_date) mnt, sum(sale) mnt_sale
    from sales
    group by mnt) n on n.mnt = s.mnt - 1
;

DB Fiddle

对我来说有点棘手,但我认为下面的代码可以正常工作

SELECT month, sale,growth_rate
FROM(
SELECT month, sale, 
       IF(@last_entry = 0, 0, ROUND(((sale - @last_entry) / @last_entry) * 100,2)) AS growth_rate,
       @last_entry := sale AS last_entry                  
FROM
      (SELECT @last_entry := 0) x,
      (SELECT month, sum(sale) sale
       FROM   (SELECT month(order_date) as month,sum(sale) as sale 
               FROM sales GROUP BY month(order_date)) monthly_sales
       GROUP BY month) y) t;

预期结果

+-------+------+-------------+
| month | sale | growth_rate |
+-------+------+-------------+
|     1 |   90 |        0.00 |
|     2 |   65 |      -27.78 |
|     3 |  105 |       61.54 |
|     4 |   55 |      -47.62 |
+-------+------+-------------+