【问题标题】:Redshift: Grouping rows by range and adding to output columnsRedshift:按范围分组行并添加到输出列
【发布时间】:2020-04-23 09:28:40
【问题描述】:

我有这样的数据:

表 1:(以 1、2、3 等表示的商品数量,销售日期以 epoch 为单位,给定日期的销售数量为 Number。数据仅涵盖最近 12 周的销售情况)

Item | Sales_Date | Number   
1    1587633401000 2  
1  1587374201000  3  
1  1585732601000  4  
1  1583054201000  1  
1 1582190201000  2   
1 1580548601000  3  

我的输出是每项单行,每列显示每个月的总销售额:

输出:

Item | Month_1_Sales | Month_2_Sales | Month_3_Sales  
1         3                 3               9  

因为唯一发生的销售发生在 1580548601000(销售额 = 3),而 1583054201000(销售额 = 1)和 1582190201000(销售额 = 2)都发生在第 2 个月等。

所以我需要按月份将销售日期分成几组,将它们的销售数字相加,然后将这些数字放在列中。我对 SQL 很陌生,所以不知道从哪里开始。有人能帮忙吗?

【问题讨论】:

  • 你如何定义? 12 周不是完整的 3 个月。

标签: sql database amazon-redshift


【解决方案1】:

您可以使用以下方法从时间戳中提取月份:

select extract(month from (timestamp 'epoch' + sales_date / 1000 * interval '1 second'))

但是,我猜您确实想要 4 周的周期,因为 12 周的数据不是完整的 3 个月。这对我来说更有意义。对于计算,使用与最早日期的差,然后使用算术和条件聚合:

select item,
       sum(case when floor((sales_date - min_sales_date) / (1000 * 60 * 60 * 24 * 4 * 7)) = 2
                then number
           end) as month_3_sales
       sum(case when floor((sales_date - min_sales_date) / (1000 * 60 * 60 * 24 * 4 * 7)) = 1
                then number
           end) as month_2_sales
       sum(case when floor((sales_date - min_sales_date) / (1000 * 60 * 60 * 24 * 4 * 7)) = 0
                then number
           end) as month_3_sales
from (select t1.*,
             min(sales_date) over () as min_sales_date
      from table1 t1
     ) t1
group by item;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多