-1

我正在努力查询数据作为示例

----------
Date of Transaction  Customer_ID    Customer_Register_Status
20/09/2015            123              NEW
21/09/2015            123              Activate
22/09/2015            123              Activate
23/09/2015            123              Suspense
24/09/2015            123              Suspense
25/09/2015            123              Activate
26/09/2015            123              Activate
27/09/2015            123              Activate
28/09/2015            123              Activate
29/09/2015            123              Activate
30/09/2015            123              Activate
26/09/2015            123              Activate
27/09/2015            ABC              NEW
28/09/2015            ABC              NEW
29/09/2015            ABC              NEW
30/09/2015            ABC              NEW
01/09/2015            ABC              NEW
02/09/2015            ABC              NEW

我的愿望结果

Date of Transaction  Customer_ID    Customer_Register_Status
25/09/2015            123              Activate
27/09/2015            ABC              NEW

结果的规则

  • 使用 Customer Register_status 必须显示最新状态
  • 日期必须是更改最后状态的第一个日期
  • 如果 Customer_Register_Status 永远不会更改显示,则必须显示交易的第一个日期

请指导我如何创建查询以获取结果

4

1 回答 1

0

您想要最后一个状态的第一个日期。. . 即切换到最后状态的日期。

这是执行以下操作的一种方法:

  • 当状态改变时创建一个标志。
  • 对标志进行前向求和以创建一个grp标识具有相同状态的相邻行。
  • 计算每个客户的最长日期。
  • 按客户和 grp 进行聚合,仅保留最大日期与客户最大日期匹配的组。

SQL 是:

select t.customer_id, min(dte), status
from (select dte, customer_id, status,
             sum(case when prev_status = status then 0 else 1 end) over (partition by customer_id) as statusgrp,
             max(dte) over (partition by customer_id) as maxdte
      from (select t.*,
                   lag(status) over (partition by customer_id order by dte) as prev_status
            from table t
           ) t
      ) t
group by customer_id, statusgrp, status, maxdte
having max(dte) = maxdte;
于 2015-10-02T16:07:22.443 回答