我有一个要求,其中我必须查询数据库以获取以下条件。
数据库[报告拉取]让我们说2列
客户 ID 报告Dt
我必须找到所有在过去 30 天内没有记录但有确切记录(今天 - 30 )的客户以及其他条件。
Select Condition on [Report Pull] PR
and cast(PR.ReportDt as Date) = cast(getdate()-30 as date)
and not exists (
select PR2.*
from [Report Pull] PR2
where 1=1
and cast(PR2.ReportDt as Date) > cast(getdate()-30 as date)
and PR2.CustomerId = PR.CustomerId
)
现在我想拉客户,这样
cast(getdate()-30 as date) is mod30 = 0
AND at the same time
cast(PR2.ReportDt as Date) > cast(getdate()-30 as date)
Next
cast(getdate()-60 as date) is mod30 = 0
AND at the same time
cast(PR2.ReportDt as Date) > cast(getdate()-60 as date)
that is no report pulled in last 60 days
以此类推,每 30 天一次。这是因为数据库可以有多个报告拉取记录。我知道这有点令人困惑,但请帮助我。:)
请注意,我们不能在SQL中声明任何变量。DB是Salesforce Marketing CLoud aka ExactTarget
我不是 100% 清楚您要做什么,但我认为您可以通过单次传递表格(无需自连接)来完成此操作。 我并不是说自我加入不好,请注意。
考虑一下:
select
CustomerID,
max (case when cast(ReportDt as Date)=cast(getdate()-30 as date) then 1 else 0 end) EQ30,
max (case when cast(ReportDt as Date)>cast(getdate()-30 as date) then 1 else 0 end) GT30,
max (case when cast(ReportDt as Date)=cast(getdate()-60 as date) then 1 else 0 end) EQ60,
max (case when cast(ReportDt as Date)>cast(getdate()-60 as date) then 1 else 0 end) GT60
from
[Report Pull]
group by
CustomerID
它应该产生一个数据集,上面写着:
Customer ID 30 Days ago? Last 30 Days 60 Days ago? Last 60 days
----------- ------------ ------------ ------------ ------------
其中 1 = 真,0 = 假。 从这里开始,我认为很容易将其扩展到其他时间范围,并逐个客户评估他们属于哪个类别。
同样,我不确定你想要的最终输出是什么,但希望这是一个适合它的概念。