这里有一个问题,我需要计算每个日期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
它继续这样下去。我需要的是每天的总和。
答案 0 :(得分:0)
以下简单的事情应该可以正常工作:
SELECT
`date`,
COUNT(DISTINCT `uid`) as `unique_visits`
FROM
`foo`
WHERE
`date` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY
`date`
答案 1 :(得分: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天的范围,然后将其加入到该表中以获取该日期范围内的所有记录并进行不同的计数以查找所有不同的用户
答案 2 :(得分: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 |
+---+----------+