如何在 sql 中创建动态 where 子句?

How to create a dynamic where clause in sql?

所以我创建了一个 table,其中包含交易 table 中的以下列,其中包含所有客户购买记录: 1. 月-年,2.Customer ID,3. 该月的交易数量。

我正在尝试创建一个 table 的输出 1. 月-年,2. 活跃客户数定义为在上一年至少购买过一次。

我目前的代码是这样的,但显然只捕获一个日期并且 where 子句不是动态的。非常感谢您的帮助。

select month_start_date, cust_ID, 
(case when month_start_Date between date and add_months(date, -12) then count(cust_ID) else 0 end) as active
from myserver.mytable
where
month_start_Date>add_months(month_start_date,-12)
group by 1,2

编辑:我只是想在客户旁边放一个标志,如果他们在每个月都活跃,定义为在去年至少有一次交易,谢谢!

您可以使用 Teradata 的专有 EXPAND ON 语法来创建时间序列:

SELECT month_start_date, COUNT(*)
FROM
 ( -- create one row for every month within the next year
   -- after a customer's transaction  
   SELECT DISTINCT
      BEGIN(pd) AS month_start_date, 
      cust_ID
   FROM myserver.mytable
   EXPAND ON PERIOD(month_start_date, ADD_MONTHS(month_start_date,12)) AS pd
       BY ANCHOR MONTH_BEGIN         -- every 1st of month
       FOR PERIOD (DATE - 500, DATE) -- use this to restrict to a specific date range
 ) AS dt
GROUP BY month_start_date
ORDER BY month_start_date