2015-07-09 189 views
0

這是我的表結構SQL嵌套邏輯

CUST_ID ORDER_DT 
1  01-2013 
1  04-2013 
1  01-2015 
1  02-2015 

我所試圖實現的是客戶爲新客戶/現有客戶和復興分類。 邏輯是 第一次命令 - 新 時間從最後一次購買在365天,那麼現有 時間超過1年,然後復活

我的輸出應該

CUST_ID ORDER_DT FLAG 
1   01-2013 New 
1   04-2013 Exisiting 
1   01-2015 Revived 
1   02-2015 Exisiting 

我的SQL

select a.cust_id,a.order_dt,coalesce(b.ptye,'other') as typ 
from tab a left join 
    (select min(order_dt),new as ptye from tab group by cust_id) b on a.cust_id=b.cust_id 

如何用嵌套邏輯替換另一個。

+0

你有沒有嘗試過什麼? – Amit

+0

你使用的是什麼SQL風格? – Amit

+0

Teradata,不能有CASE陳述與選擇 – sai

回答

1

這個想法的方式是使用lag()。 Teradata並不完全支持延遲,但它確實支持其他窗口功能。所以,你可以模仿它:

select t.cust_id, t.order_dt, 
     (case when order_dt - prev_od <= 365 then 'Existing' else 'New' 
     end) as flag 
from (select t.*, 
      max(order_dt) over (partition by cust_id order by order_dt 
           rows between 1 preceding and 1 preceding 
           ) as prevod 
     from mytable t 
    ) t; 

我要指出,你實際上並不需要的子查詢,但我認爲它有助於可讀性:

select t.cust_id, t.order_dt, 
     (case when order_dt - 
        max(order_dt) over (partition by cust_id order by order_dt 
           rows between 1 preceding and 1 preceding 
           ) <= 365 
      then 'Existing' else 'New' 
     end) as flag 
from (select t.*, 
       as prevod 
     from mytable t 
    ) t; 
0

一個非常簡單的方法來做到這一點是使用一個case語句與子查詢:

select cust_id 
, order_dt 
, flag = case 
      when (select COUNT(*) from myTable x where t.cust_id= x.cust_id and x.order_dt < t.order_dt and DATEDIFF(DD, x.order_dt , t.order_dt) < 365) then 'Existing' 
      when (select COUNT(*) from myTable x where t.cust_id= x.cust_id and x.order_dt < t.order_dt and DATEDIFF(DD, x.order_dt , t.order_dt) >= 365) then 'Revived' 
      else 'New' 
     end 
from myTable t 
+0

我正在使用teradata,並且在CASE表達式的WHEN子句中出現'3771非法表達式'。 – sai

0

這包括「起死回生」,其邏輯在戈登的答案中失蹤了:

SELECT 
    CUST_ID, ORDER_DT, 
    CASE 
     WHEN ORDER_DT = MIN(ORDER_DT) -- first order 
         OVER (PARTITION BY CUST_ID) 
     THEN 'New' 
     WHEN ORDER_DT >= MAX(ORDER_DT) -- more than 365 days since previous order 
         OVER (PARTITION BY CUST_ID 
          ORDER BY ORDER_DT 
          ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) + 365 
     THEN 'Revived' 
     ELSE 'Existing' 
    END 
FROM tab