MySQL查询在移动DATE期间检索DISTINCT COUNT

时间:2012-09-27 23:59:48

标签: mysql sql count distinct between

我正在尝试编写一个查询,该查询返回每个日期之前7天的日期列表和DISTINCT COUNT个用户ID。我正在使用的表很简单,看起来像这样:

Started                 UserId
"2012-09-25 00:01:04"   164382
"2012-09-25 00:01:39"   164382
"2012-09-25 00:02:37"   166121
"2012-09-25 00:03:35"   155682
"2012-09-25 00:04:18"   160947
"2012-09-25 00:08:19"   165806

我可以编写单个COUNT输出的查询,如下所示:

SELECT COUNT(DISTINCT UserId)
FROM Session 
WHERE Started BETWEEN '2012-09-18 00:00' AND '2012-09-25 00:00';

但是我要做的是在表格和之前的7天内每天输出此COUNT。为了澄清,9月25日的值将是18日到25日之间DISTINCT用户ID的数量,第24和第24日之间的第24个等等。

我尝试了以下查询,但它每天只提供COUNT:

SELECT 
DATE(A.Started),
Count(DISTINCT A.UserId)
FROM Session AS A
WHERE DATE(A.Started) BETWEEN DATE(DATE_SUB(DATE(DATE(A.Started)),INTERVAL 7 DAY)) AND DATE(DATE(A.Started))
GROUP BY DATE(A.Started)
ORDER BY DATE(A.Started);

输出如下:

DATE(A.Started) "Count(DISTINCT A.UserId)"
2012-09-18          709
2012-09-19          677
2012-09-20          658
2012-09-21          556
2012-09-22          530
2012-09-23          479
2012-09-24          528
2012-09-25          480
...

但正如我所说,这些只是每日计数。最初我认为我可以将7天的值相加,但这将使DISTINCT子句无效。 我需要在给定日期之前的每7天内使用DISTINCT UserId计数。

2 个答案:

答案 0 :(得分:1)

此查询应该适合您:

SELECT
    DATE_FORMAT(d1.Started, '%Y-%m-%d') AS Started,
    COUNT(DISTINCT d2.UserID) Users
FROM
(
    SELECT
        DATE(Started) AS Started
    FROM
        Session
    GROUP BY
        DATE(Started)
) d1 
INNER JOIN
(
    SELECT DISTINCT
        DATE(Started) AS Started,
        UserID
    FROM
        Session
) d2
ON d2.Started BETWEEN d1.Started - INTERVAL 7 DAY AND d1.Started
GROUP BY
    d1.Started
ORDER BY
    d1.Started DESC

访问http://sqlfiddle.com/#!2/9339c/5以查看此查询的实际效果。

答案 1 :(得分:-1)

尝试:

Select Distinct Date(A.Started), Count(B.UserId)
From Session a
    Join Session b 
        On b.Start Between AddDate(A.Start, day, -7) And A.Start

我不是MySQL人,所以语法可能不正确,但模式会起作用....