如何编写查询以返回每日返回的用户?

时间:2016-06-30 08:38:08

标签: mysql sql

我有一个非常简单的表phone_calls,其中包含以下列:

id, timestamp, phone_number

如何编写一个返回每日返回用户数的查询?它应该有两列:

Date, Number of Returning Users

返回用户:

任何指定日期的返回用户D是在D之前至少打过一次电话的人。

在D上多次通话但在D之前没有被叫过的用户不会被计为返回用户。

更新

所以这就是我的尝试:

SELECT DATE(timestamp) AS date, COUNT(DISTINCT phone_number) AS user_count
FROM phone_calls
WHERE phone_number IN (SELECT phone_number FROM phone_calls GROUP BY phone_number HAVING COUNT(consumer_id) > 1)
GROUP BY DATE(timestamp)

但它不是一个正确的解决方案,因为它不符合上述返回用户的定义。

我在苦苦挣扎?

对于任何指定日期,如何过滤那些从未在当天之前拨过的计数中的电话号码?

2 个答案:

答案 0 :(得分:2)

SELECT 
    DATE(timestamp) AS date,
    COUNT(DISTINCT phone_number) AS     user_count
FROM 
    phone_calls pc
WHERE EXISTS (
    SELECT *
    FROM phone_calls pc1
    WHERE 
        pc1.phone_number = pc.phone_number AND
        DATE(pc1.timestamp) < DATE(pc.timestamp)
    )
GROUP BY DATE(pc.timestamp)

答案 1 :(得分:0)

更新了尝试此查询

 Select date(pc.timestamp) AS RDate ,count(*)  
from phone_calls pc INNER JOIN phone_calls pcc
on pcc.phone_number=pc.phone_number 
and date(DATE_ADD(pcc.timestamp, INTERVAL -1 DAY))= DATE (pc.timestamp)  group by DATE (pc.timestamp);