SQL - 如果日期在加入 - 更改日期期间不匹配,则加入

时间:2015-11-18 22:43:18

标签: sql postgresql jointable

我正在使用POSTGRESQL并创建一个表格,该表格可以加入adwords数据和salesforce数据,以便从费用/展示次数中获得我的指标的完整视图,以便在salesforce(广告系列成员记录)中形成填充。我们可以将这两件事(salesforce和adwords)与UTM参数结合起来,这个UTM参数就是" adgroup" adwords中的值,并成为" marketing_content_stamp__c"在salesforce中。问题是我们已经创建了一个cookie,其中说明了如果这个人是有机的,那么从他们在这里的最后一天开始,在人员cookie中查找存储的UTM值"。这会产生一个问题,因为有时我们在salesforce中填写表格,其中包含广告组没有记录的日期。

我想做什么: 加入表并说出"如果我的表格中存在表单填充" temp.adwords_sf"并且广告组表没有该日期的记录,请将记录加入上一个广告组记录日期。"

例如,我在11月13日的日期为我的ADGROUPX提供了一个表单,但我点击的最后一条记录是11/11。我想这样做,以便填写记录与11/11相关联,否则它将不会显示。

SQL QUERY:

drop table temp.adwords_ui;
Create table temp.adwords_ui as(
Select 
cast(date as date),
Case 
WHEN adgroup like '%-uk-%' then 'UK'
WHEN adgroup like '%-usa-%' then 'USA'
WHEN adgroup like '%-us-%' then 'USA'
END AS Target_Country,
Case 
WHEN adgroup like '%-product-social%' then 'Product-SocialNetworks'
WHEN adgroup like '%-product-solu%' then 'Product-Solutions'
WHEN adgroup like '%-brand-%' then 'Brand'
WHEN adgroup like '%-competitors-%' then 'Competitors'
END AS ad_grouping,
adgroup,
sum(adcost) as cost,
sum(impressions) as impressions,
sum(adclicks) as clicks
from rjm_current.adwords45309635_v2
where adcost <> 0 
and date > '11/3/2015'
group by 1,2,3,4);


drop table temp.adwords_sf;
Create table temp.adwords_sf as (
Select
id,
campaign_name__c as campaign,
marketing_content_stamp__c as marketing_content,
cast(firstrespondeddate as date) as form_fill_date,
count(*) as form_fills
from rjm_current.sf_campaignmember
where marketing_source_stamp__c = 'google-adwords'
and firstrespondeddate > '11/3/2015'
group by 1,2,3,4); 


drop table custom.adwords;
Create table custom.adwords as (
select
a.date,
a.target_country,
a.ad_grouping,
a.adgroup,
b.campaign,
a.cost,
a.impressions,
a.clicks,
b.form_fills
--((a.cost) / nullif(a.clicks,0)) as CPC,
--(a.clicks / a.impressions) as CTR,
--((a.cost) / nullif(b.form_fills,0)) as Cost_per_FormFill
from temp.adwords_ui a
Left Join temp.adwords_sf b on a.adgroup = b.marketing_content
and cast(a.date as date) = cast(b.form_fill_date as date)
);

1 个答案:

答案 0 :(得分:0)

我认为它会变得混乱......

您可以识别出错过的&#39;行将其更改为右连接,然后添加&#39;其中a.date为空&#39;

为每个&#39; a&#39;添加一列。列,如下面的子查询(日期列的示例)

(select top 1 date 
from a where date < b.form_filled_date 
and a.adgroup = b.marketing_content
order by date desc) as a_date,

(select top 1 target_country
from a where date < b.form_filled_date 
and a.adgroup = b.marketing_content
order by date desc) as a_target_country,

将上述内容写入临时表,然后将其涂抹到自定义表的末尾!

希望无论如何都能让你开始......