2017-02-02 8 views
1

私は、以下の条件のためにデータベースをクエリする必要があります。n回使用してデータベースからデータを取得する

データベース[レポートプル]は、私が過去30日間のレコードを持っていないすべての顧客を見つけるために持っていますが、正確に記録を持っている私たちは2列
得意ReportDt

を言わせました(今日 - 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 
) 

は、今私は、30日ごとにこのようなこと

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 

などを顧客を引っ張って欲しいです。これは、dbに複数のレポート・プルのレコードを含めることができるためです。 少し混乱していますが、私を助けてください。 :)

SQLで変数を宣言することはできませんのでご注意ください。 DBはSalesforceマーケティングです。CLoud別名ExactTarget

答えて

0

あなたは何をしようとしているのかについて100%明確ではありませんが、私はあなたがテーブルの1回のパスでこれを達成できると思います。私は自己結合が悪いと言っているわけではありません。

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 =偽を

が、この考えてみましょう。ここから、これを他の時間枠に合わせてスケーリングし、どのカテゴリに属する​​のかを顧客ごとに評価するのはかなり簡単だと思います。

また、最終的な出力には何を望みますか?これはそれに役立つ概念です。

関連する問題