Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql计数结果在前几个月中尚未出现_Mysql_Sql_Join_Left Join - Fatal编程技术网

mysql计数结果在前几个月中尚未出现

mysql计数结果在前几个月中尚未出现,mysql,sql,join,left-join,Mysql,Sql,Join,Left Join,我有两张桌子,一张桌子是“月”,一张桌子是“广告”。我想得到所有不同的电子邮件从广告每月这些电子邮件还没有算在今年的前几个月 我今天有这样的sthg: SELECT months.id_month, Count(DISTINCT ad.email) FROM `months` LEFT JOIN `ad` ON id_month = Month(ad.created_at) AND Year(ad.created_at) = 2015 GROUP BY id_month OR

我有两张桌子,一张桌子是“月”,一张桌子是“广告”。我想得到所有不同的电子邮件从广告每月这些电子邮件还没有算在今年的前几个月

我今天有这样的sthg:

SELECT months.id_month, Count(DISTINCT ad.email) 
FROM  `months` 
LEFT JOIN `ad` 
  ON id_month = Month(ad.created_at) 
 AND Year(ad.created_at) = 2015 
GROUP BY id_month 
ORDER BY id_month ASC 
输出:

但12月份,发现的3封不同的电子邮件已经在11月份,12月份的预期输出应该是0


有什么想法吗?

嗯。听起来你想统计每年第一次出现电子邮件的次数。如果是,则使用两个聚合:

SELECT m.id_month, Count(ad.email) 
FROM  months m LEFT OUTER JOIN
      (SELECT ad.email, MIN(ad.created_at) as created_at_2015
       FROM `ad` 
       WHERE Year(ad.created_at) = 2015 
       GROUP BY ad.email
      ) ad
      ON m.id_month = Month(ad.created_at_2015) 
GROUP BY m.id_month 
ORDER BY m.id_month ASC ;

准备样本数据这里是样本数据:复制案例的样本数据