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

0yycz8jy  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(313)

我有一张table sales 用一些 columns 以及 data 这样地:

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 .
有谁能帮我或给我一些线索来实现这一点吗?

pkwftd7m

pkwftd7m1#

有点复杂:

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
;

小提琴

gajydyqb

gajydyqb2#

可以使用聚合和窗口函数。类似于他的:

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
7z5jn7bk

7z5jn7bk3#

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

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 |
+-------+------+-------------+

相关问题