SQL 计算创建日期前 6 个月的不同调用次数

SQL count distinct # of calls 6 months prior to create date

我正在尝试找出 SQL 到:

  1. 计算不同调用的数量
  2. 在创建帐户前 6 个月在帐户上创建

我还需要 CAST 日期字段。 我在想:

case when (call_date as date format 'MM/DD/YYYY') 
between (create_date as date format 'MM/DD/YYYY') and 
(ADD_MONTHS, (create_date as date format 'MM/DD/YYYY), -6) 
then COUNT (DISTINCT call_nbr) as calls

这是我正在处理的数据片段。我需要3个电话的答案。

注意:数据库中的两个日期都被标记为 table DATE 格式。

我想你想要:

select count(distinct call_nbr) no_calls
from mytable
where call_date >= add_months(create_date, -6)

如果您有一个列表示 account_id,那么您可以使用 group by 子句来获取每个帐户 的调用次数:

select account_id, count(distinct call_nbr) no_calls
from mytable
where call_date >= add_months(create_date, -6)
group by account_id

编辑:您似乎想要条件聚合:

select 
    account_id, 
    count(distinct case when call_date >= add_months(create_date, -6) then call_nbr end) no_calls
from mytable
group by account_id