隔离值变为 0 的日期并从该日期开始聚合另一个值

Isolating the date a value turns 0 and aggregating another value from that date back

我想看两件事:

  1. 客户关闭我们的所有账户时(日期 帐户变为 0)
  2. 客户与我们的总互动次数 直到那一点(账户是一个时的交互总和 大于一的数字)。

客户与我们的总互动次数 直到那一点(账户是一个时的交互总和 大于一的数字)。

基本上我试图从附图中的顶部 table 到底部 table。

Customer    month   Accounts    Interactions
12345      Jan-15   3           5
12345      Feb-15   3           1
12345      Mar-15   2           7
12345      Apr-15   1           3
12345      May-15   1           9
12345      Jun-15   1           2
12345      Jul-15   0           3
67890      Feb-15   1           4
67890      Mar-15   1           4
67890      Apr-15   1           9
67890      May-15   0           5


Customer    Month close date    Interactions    
12345           Jul-15              30  
67890           May-15              23  

当我第一次阅读这个问题时,听起来好像会有一个带有 window 函数的巧妙解决方案,但在重新阅读之后,我认为没有必要。假设关闭他的最后一个帐户将是客户与您的最后一次互动,您只需要每个客户的最后一次互动日期,这意味着这个问题可以通过简单的聚合函数解决:

SELECT   customer, MAX(month), SUM(interactions)
FROM     mytable
GROUP BY customer

要获取最近三个月的数据,您需要一个 OLAP 函数:

SELECT Customer, MAX(months), SUM(Interactions)
FROM
 ( 
   SELECT Customer, month, Interactions
   FROM     mytable
   QUALIFY
   -- only closed accounts
       MIN(Accounts) OVER (PARTITION BY Customer) = 0

   -- last three months
   AND month >= oADD_MONTHS(MAX(month) OVER (PARTITION BY Customer), -3)
 ) AS dt
GROUP BY customer