SQL嵌套逻辑

时间:2015-07-09 21:50:52

标签: sql logic teradata

这是我的表结构

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

如何用嵌套逻辑替换另一个。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

答案 2 :(得分: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
相关问题