单个MySQL select语句中的“distinct count”和“distinct count if if exists”

时间:2013-10-11 12:42:24

标签: mysql sql

我有一张电子邮件表,我已发送电子邮件以及发送电子邮件的日期。

-----------------------------
|   email   |   date_sent   |
-----------------------------
|  a@a.com  |  2013-01-10   | 
|  a@a.com  |  2013-01-10   |
|  a@a.com  |  2013-01-10   |
|  b@b.com  |  2013-01-10   |
|  a@a.com  |  2013-01-11   |
|  c@c.com  |  2013-01-11   |
-----------------------------

对于给定日期,我需要计算发送的电子邮件总数,今天的唯一地址以及之前未出现的唯一地址。

第一部分很简单:

SELECT count(email) emails_sent, count(distinct email) unique_users
from sent_emails where date_sent = '2013-01-10';

我无法收到以前没有出现过的电子邮件。有可能吗?

我尝试了许多不同的方法,但收效甚微。 e.g:

SELECT count(email) emails_sent, count(distinct email) unique_users,
sum( (select count(email) from sent_emails se
where se.date_sent < date_sent 
and se.email = email)) new_emailed_users
from sent_emails where date_sent = '2013-01-10';

我确信这是可能的。

这就是我期望的结果是2013-01-10:

--------------------------------------------------
| emails_sent | unique_users | new_emailed_users |
--------------------------------------------------
|      4      |      2       |         2         |
--------------------------------------------------

这就是我期望的结果是2013-01-11:

--------------------------------------------------
| emails_sent | unique_users | new_emailed_users |
--------------------------------------------------
|      2      |      2       |         1         |
--------------------------------------------------

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

没有子查询,提高速度

select
count(if(date_sent='2013-01-10',email, null)) as emails,
count(distinct if(date_sent='2013-01-10',email, null)) as uniques,
count(distinct email) as total_unique_email
from sent_emails

答案 1 :(得分:-1)

这是我的解决方案。不确定它是最有效的:

SELECT count(email) emails_sent, count(distinct email) unique_users,
count(distinct if(not exists(select 1 from sent_emails where  date_sent < se.date_sent and se.email = email ),email,null)) new_emailed_users
from sent_emails se where date_sent = '2013-01-10';