[英]“distinct count” and “distinct count if exists” in single MySQL select statement
I have a table of emails that I have sent along with the date I sent the email. 我有一张已发送的电子邮件表格以及发送电子邮件的日期。
-----------------------------
| 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 |
-----------------------------
For a given date I need to get a count of the total emails sent, the unique addresses for today and the unique addresses that haven't appeared before. 对于给定的日期,我需要统计发送的电子邮件总数,今天的唯一地址和以前从未出现过的唯一地址。
The first part is easy: 第一部分很简单:
SELECT count(email) emails_sent, count(distinct email) unique_users
from sent_emails where date_sent = '2013-01-10';
I am having trouble getting the emails that haven't appeared before. 我在收到以前没有出现过的电子邮件时遇到了麻烦。 Is it possible?
可能吗?
I have tried many different ways with little to no success. 我尝试了许多不同的方法,但几乎没有成功。 eg:
例如:
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';
I'm sure this is possible. 我相信这是可能的。
This is what I expect the result to be for 2013-01-10: 这是我期望2013年1月10日的结果:
--------------------------------------------------
| emails_sent | unique_users | new_emailed_users |
--------------------------------------------------
| 4 | 2 | 2 |
--------------------------------------------------
This is what I expect the result to be for 2013-01-11: 这是我预期2013年1月11日的结果:
--------------------------------------------------
| emails_sent | unique_users | new_emailed_users |
--------------------------------------------------
| 2 | 2 | 1 |
--------------------------------------------------
Thanks for any help 谢谢你的帮助
without a subquery, improving speed 没有子查询,提高速度
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
Here is my solution. 这是我的解决方案。 Not sure it is the most efficiant:
不确定它是否最有效:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.