我有一个表A,它包含每个月帐户的相关数据,每个月可能有多个条目,下面的数据如代码片段所示。

期望转换表
我想要生成如下所示的表。其思想是,对于表A(配置)中的每个不同的account_id,希望生成一个汇总表,以便每个account_id在日历年度的每个月都有一个汇总条目,该月份的最新/最后一个account_id条目决定帐户是否处于活动状态。对于没有特定月份分录的帐户,ACTIVE列的值将为空。

如能就如何实现这一目标提供任何投入,将不胜感激。谢谢。
发布于 2020-11-07 12:55:09
首先,您可以使用以下方法生成雪花中的日期:
select dateadd(month, seq4, '2020-01-01') as dte
from table (generator(rowcount => 12))因此,我们的想法是做以下工作:
lag(ignore nulls)来获得结果。所以:
with months as (
      select dateadd(month, seq4, '2020-01-01') as mon
      from table (generator(rowcount => 12))
     )
select a.account_id, m.mon,
       coalesce(t.active,
                lag(t.active ignore nulls) over (partition by a.account_id order by m.mon)
               ) as active
from (select distinct account_id from t) a cross join
     months m left join
     (select mon, account_id,
             max(case when seqnum = 1 then active end) as active
      from (select t.*, date_trunc('month', time) as mon,
                   row_number() over (partition by account_id, date_trunc('month', time) order by time desc) as seqnum
            from t
           ) t
     ) t
     on t.mon = m.mon and t.account_id = a.account_idhttps://stackoverflow.com/questions/64724539
复制相似问题