【问题标题】:Calculate month on month growth rate of orders for the last 3 months for each country计算每个国家过去 3 个月的订单月环比增长率
【发布时间】:2021-12-24 11:06:03
【问题描述】:

我正在尝试查找每个国家/地区过去 3 个月的订单月增长率。 到目前为止,我已经尝试过:

select date_part('month', order_date) as mnth,
country_id,
100 * (count() - lag(count(), 1) over (order by order_date)) / lag(count(), 1) over (order by order_date) as growth
from orders
and order_date >= DATEADD(DAY, -90, GETDATE())
group by country_id;

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    当我们 GROUP BY country_id 时,我们会生成一个行结果,每个国家/地区一个。

    然后,聚合 COUNT 将对每个国家/地区的一组进行运算,随后的窗口函数 (LAG) 将不会看到每个国家/地区的多于一行。

    在这种情况下,LAG 无法用于获取同一国家/地区上个月的数据。

    GROUP BY country_id, date_part('month', order_date) 是一种可以使用的方法。请务必按日期排序每个国家/地区的 LAG OVER PARTITION。

    这是您的 SQL 中的一个小改动,可能会有所帮助(未经测试,只是一个起点)。

    注意:我在下面使用 SQL Server 进行测试。根据需要将datepart 转换为date_part

    Fiddle for SQL Server

    WITH cte AS (
            SELECT *, datepart(month, order_date) AS mnth
              FROM orders
             WHERE order_date >= DATEADD(DAY, -90, GETDATE())
         )
    SELECT mnth
         , country_id
         , 100 * (COUNT(*) - LAG(COUNT(*)) OVER (PARTITION BY country_id ORDER BY mnth)) / LAG(COUNT(*)) OVER (PARTITION BY country_id ORDER BY mnth) AS growth
      FROM cte
     GROUP BY country_id, mnth
    ;
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2020-05-29
      相关资源
      最近更新 更多