-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

最後のステータスの最初の日付が必要です。. . つまり、最後のステータスに切り替わった日付です。

以下は、次のことを行う 1 つの方法です。

  • ステータスが変化したときにフラグを作成します。
  • フラグの前方合計を作成し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 に答える