-1

这里有一个问题,我需要计算每个日期 30 天的 unque 用户总数。我的意思是今天它是今天 - 30 天范围之间的唯一性总和,昨天它是昨天 - 30 天等等。表结构为:

date        uid   visits
27-06-2013   11     40
27-06-2013   14     40
26-06-2013   13     45
25-06-2013   11     20
24-06-2013   12     40

就这样继续下去。我需要的是每天的总和。

4

3 回答 3

0

像下面这样简单的东西应该可以正常工作:

SELECT
    `date`,
    COUNT(DISTINCT `uid`) as `unique_visits`
FROM
    `foo`
WHERE
    `date` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY
    `date`

SQLFiddle 演示

于 2013-07-02T10:33:57.510 回答
0

假设我已经正确阅读了您的问题并且您的日期字段的数据类型为日期,那么可能是这样的:-

SELECT Sub1.EndDate, COUNT(DISTINCT a.uid)
FROM SomeTable a
INNER JOIN
(
    SELECT DISTINCT date AS EndDate, DATE_SUB(date, INTERVAL 30 DAY) AS StartDate
    FROM SomeTable
) Sub1
ON a.date BETWEEN Sub1.StartDate AND Sub1.EndDate

这是使用子选择来获取 30 天的每个范围,然后将其加入到表中以获取该日期范围内的所有记录并进行不同的计数以查找所有不同的用户

于 2013-07-02T10:37:07.430 回答
0
Consider this example. It provides a rolling sum on values within 3 points of the current value

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT x.i, SUM(y.i) FROM ints x JOIN ints y ON y.i BETWEEN x.i-3 AND x.i GROUP BY x.i;
+---+----------+
| i | SUM(y.i) |
+---+----------+
| 0 |        0 |
| 1 |        1 |
| 2 |        3 |
| 3 |        6 |
| 4 |       10 |
| 5 |       14 |
| 6 |       18 |
| 7 |       22 |
| 8 |       26 |
| 9 |       30 |
+---+----------+
于 2013-07-02T11:46:53.817 回答