【问题标题】:Aggregate data based on fixed moving date window in Presto在 Presto 中基于固定移动日期窗口聚合数据
【发布时间】:2021-09-10 12:39:17
【问题描述】:

我想:

  1. “3 个月”滚动窗口中的汇总数字,(例如 1 月至 3 月、2 月至 4 月、3 月至 5 月......)
  2. 然后将同一国家和城市与去年的同一滚动窗口进行比较

我已经有表:(唯一的:国家 + 城市 + 月份级别)

country    city     month       sum
US         A        2019-03-01  3
US         B        2019-03-01  4
DE         C        2019-03-01  5
US         A        2019-03-01  3
CN         B        2019-03-01  4
US         B        2019-04-01  4
UK         C        2019-04-01  7
US         C        2019-04-01  2
....
US         A        2019-12-01  10
US         B        2020-12-01  6
US         C        2021-01-01  7

第一步理想输出:

country    city     period                     sum
US         A        2019-03-01~2019-05-01      XXX
US         A        2019-04-01~2019-06-01      YYY
UK         A        2019-03-01~2019-05-01      ZZZ
...
UK         A        2020-12-01~2021-02-01      BBB

第2步理想输出:

country    city     period                     sum    last_year_sum   year_over_year_%
US         A        2019-03-01~2019-05-01      XXX    111              40%
US         A        2019-04-01~2019-06-01      YYY    1111             30%
UK         A        2019-03-01~2019-05-01      ZZZ    11111            20%
...
UK         A        2020-12-01~2021-02-01      BBB    1111             15%

理想情况下,我想在 Presto 中实现这一点 - 知道该怎么做吗?谢谢!!

【问题讨论】:

    标签: sql aggregate-functions window-functions presto


    【解决方案1】:

    很遗憾,Presto 不支持使用日期的 range 窗框规范。一种方法是使用连接和聚合,然后使用lag() 来获取去年的金额:

    select t.country, t.city, t.sum,
           sum(t2.sum) as this_year_sum,
           lag(sum(t2.sum), 12) over (partition by country, city order by month) as prev_year_sum,
           (-1 + 
            sum(t2.sum) /
            lag(sum(t2.sum), 12) over (partition by country, city order by month)
           ) as yoy_increase
    from t left join
         t t2
         on t2.country = t.country and
            t2.city = t.city and
            t2.month >= t.month and
            t2.month <= t.month + interval '2' month
    group by t.country, t.city, t.sum;
    

    注意:这假设您拥有每个 country/city 组合的所有月份的数据。

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 2018-08-11
      • 2017-01-18
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多