如何在不同的成对行之间找到天数?

时间:2012-09-01 02:39:40

标签: mysql sql

在没有PHP代码的一个查询中,我一直在讨论如何做到这一点。

简而言之,我有一张记录电子邮件活动的表格。为了这个例子,这里是数据:

recipient_id     activity     date
1                delivered    2011-08-30
1                open         2011-08-31
2                delivered    2011-08-30
3                delivered    2011-08-24
3                open         2011-08-30
3                open         2011-08-31

目标:我想向用户显示一个数字,告诉用户在24小时内打开电子邮件的数量。

E.G。 “24小时内打开电子邮件的用户:13位读者”

对于上面的样本数据,该值将为“1”。 (接收者收到了一封电子邮件,并在第二天打开了。收件人2从未打开过,收件人3等了5天。)

有人能想出在单个查询中表达目标的方法吗?

提醒:为了统计,此人必须拥有“已发送”标记和至少一个“开放”标记。每个“开放”标签仅对每个收件人计算一次。

**编辑**抱歉,我正在使用MySQL

3 个答案:

答案 0 :(得分:2)

这是mysql中的一个版本。

select count(distinct recipient_id)
from email e1
where e1.activity = 'delivered'
  and exists
        (select * from email e2
         where e1.recipient_id = e2.recipient_id
           and e2.activity = 'open'
           and datediff(e2.action_date,e1.action_date) <= 1)

基本原则是您希望在24小时内为收件人找到已开放的行。

datediff()是在mysql中进行日期算术的好方法 - 其他dbs会因此步骤的确切方法而异。其余的sql可以在任何地方使用。

SQLFiddle:http://sqlfiddle.com/#!2/c9116/4

答案 1 :(得分:0)

未经测试,但应该有效;)不知道您使用的是哪种SQL方言,所以我使用了TSQL DATEDIFF函数。

select distinct opened.recipient_id -- or count(distinct opened.recipient_id) if you want to know number
from actions as opened 
inner join actions as delivered 
on opened.recipient_id = delivered.recipient_id and delivered.activity = 'delivered'
where opened.activity = 'open' and DATEDIFF(day, delivered.date, opened.date) <= 1

编辑:我很困惑打开了已交付 - 现已更换。

答案 2 :(得分:0)

假设:MySql,表称为“TABLE”

好吧,我不是百分之百,因为我没有表格的副本来反对,但我认为你可以做这样的事情:

SELECT COUNT(DISTINCT t1.recipient_id) FROM TABLE t1
INNER JOIN TABLE t2 ON t1.recipient_id = t2.recipient_id AND t1.activity != t2.activity
WHERE t1.activity in ('delivered', 'open') AND t2.activity in ('delivered', 'open')
AND ABS(DATEDIFF(t1.date, t2.date)) = 1

基本上,您正在将表连接到自身,其中活动不匹配,但是recipient_ids执行,状态为“已传递”或“打开”。你最终得到的结果如下:

1 delivered 2011-08-30 1 open 2011-08-31

然后你在两个日期之间进行差异(具有绝对值,因为我们不知道它们将处于哪个顺序)并确保它等于1(或24小时)。