如何绕过 teradata 中不存在的情况?

How to by pass case not when exists in teradata?

所以我创建了一个 table,其中包含来自交易 table 的以下列以及所有客户购买记录:

  1. 月-年,
  2. 客户 ID
  3. 该月的交易数量

我正在尝试创建一个 table 输出为 1.Month-Year, 2.Number of churned customers in那个月 定义为在过去 12 个月内没有进行过交易的客户。 (因此,如果客户在 2014 年 1 月只购买了一次商品,那么他们将在 2015 年 2 月流失。

如果此人在 2015 年 3 月有交易,但 none 直到 2016 年 5 月,那么他们在 2016 年 4 月再次流失。

如有任何建议,我将不胜感激。


我编写的代码在 SQL 中有效,但在 Teradata 中无效:

select 
month_start_date, 

    (select  1 
     from merchantengagement1 t2 
      where 
          t2.month_start_date >= t.month_start_date - INTERVAL '1' YEAR and
              t2.month_start_date < t.month_start_date and 
              transactions > 0  and 
              t.rcvr_ID = t2.rcvr_ID
    ) then 1 else 0 end) as churnedCustomers
from 
merchantengagement1  t
group by month_start_date

嗯,由于语法错误(没有 CASE),您现有的查询将不会 运行,否则它在 Teradata 中有效。

但是有两个问题:

  • 添加间隔时切勿使用 YEARMONTH(这可能会导致月末日期无效),请改用 ADD_MONTHS
  • 像这样的相关子查询在所有 DBMS 中都很糟糕,但在 Teradata 中尤其糟糕,导致产品连接。

你的逻辑可以用OLAP函数来表达,检查下一笔交易是否提前12个月以上或者最新一笔交易是否超过12个月前:

SELECT rcvr_ID,
   -- if this date is before the next transaction it's a churn
   ADD_MONTHS(month_start_date, 12) AS churn_date
FROM merchantengagement1
WHERE transactions > 0
QUALIFY -- more than 12 months difference
   churn_date <
   COALESCE(MAX(month_start_date) -- next transaction
            OVER (PARTITION BY rcvr_ID
                  ORDER BY month_start_date
                  ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
           , CURRENT_DATE)        -- or today

顺便说一句,没有名为 SQL 的 DBMS(当然,Microsoft 试图将其与他们的产品相关联)