今天碰到一个问题,分析一个广告主采用关键词定向于未使用关键词两种情况的收入,表结构如下:
日期,广告主ID,关键词定向,收入
20170526 A 人群定向 20元
20170526 a 学历,地域 10元
select 日期,sum(收入) from table where 关键词定向 like ‘%人群定向%’ group by 日期
select 日期 ,sum(收入) from table where 广告主ID in (select 广告主ID from table where 关键词定向 like ‘%人群定向%’ ) and 关键词定向 not like "关键词定向";
第一部分结果正确,第二部分不正确
第二部分收入会多算,因为 要算筛选当日非人群定向的收入,如果是用in会增加非当日的广告主ID的数目,所以,收入会比正确值大。
正确的计算方式为:
select 日期 ,sum(收入) from table where 广告主ID in (select 广告主ID from table where 关键词定向 like ‘%人群定向%’ group by 日期) as t1 and 日期 = t1.日期 and 关键词定向 not like "关键词定向";
或者
select 日期 ,sum(收入) from table where 广告主ID left join (select 日期,广告主ID from table where 关键词定向 like ‘%人群定向%’ group by 日期)as t1 on 日期 = t1.日期 and 广告主ID in t1.广告主ID and 关键词定向 not like "关键词定向";