每个日期获得一些新用户

时间:2014-05-08 18:11:34

标签: sql group-by

我的SQL技能低得多,我正在努力应对看似简单的任务。我正在尝试获取每个日期访问我们网站的新用户数量的报告。

这是我的统计表:

    | Date  | userid |
    +-------+-------+|
    | date1 | user1  |
    | date1 | user1  |
    | date1 | user2  |
    | date2 | user1  |
    | date2 | user3  |
    | date3 | user2  |
    | date3 | user4  |
    | date4 | user3  |

我需要一个记录集,其记录看起来像这样:

| Date  | New users on that date |
+-------+------------------------+    
| date1 | 2                      |
| date2 | 1                      |
| date3 | 1                      |
| date4 | 0                      |

我有一种感觉,我需要在每个日期明确地对用户进行分组,但我对实际实现感到绊倒......

1 个答案:

答案 0 :(得分:1)

尝试这样的事情,它会计算没有上一个日期记录的用户数量(SQL Fiddle demo):

SELECT Date, COUNT(*) as NewUsers
FROM Stats s1
WHERE NOT EXISTS
(
    SELECT 1
    FROM Stats s2
    WHERE s2.userid = s1.userid
    AND s2.Date < s1.Date
)
GROUP BY Date

注意,如果要显式获取“0”值,则必须重新加入统计表(SQL Fiddle demo):

SELECT s.Date, COALESCE(x.NewUsers, 0) AS NewUsers
FROM Stats s
LEFT OUTER JOIN
(
    SELECT Date, COUNT(*) as NewUsers
    FROM Stats s1
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM Stats s2
        WHERE s2.userid = s1.userid
        AND s2.Date < s1.Date
    )
    GROUP BY Date
) x ON s.Date = x.Date

或者,您可以使用COUNT而不是MIN,这可能会使用正确的索引(SQL Fiddle demo)获得更高的性能:

SELECT Date, COUNT(*)
FROM
(
    SELECT MIN(Date) AS Date, userid
    FROM Stats
    GROUP BY userid
) x
GROUP BY Date