MySQL查询获取总访问次数超过特定总和的日期

时间:2013-06-27 18:42:19

标签: mysql sql

我有一个表格,可存储不同网站的每日指标。表格的一个例子:

DomainStats

|DomainId |     StatPullTime    | Visits |
+---------+---------------------+--------+
    1     | 2013-06-20 00:00:00 |  500   |
    1     | 2013-06-21 00:00:00 |  500   |
    1     | 2013-06-22 00:00:00 |  500   |
    1     | 2013-06-23 00:00:00 |  500   |
    1     | 2013-06-24 00:00:00 |  500   |
    1     | 2013-06-25 00:00:00 |  500   |
    1     | 2013-06-26 00:00:00 |  500   |
    1     | 2013-06-27 00:00:00 |  1000  |

所以我需要创建一个从今天开始的查询,然后每天返回,直到访问总和大于2999.

在示例表中,它将返回2013-06-23。

这是我能想到的最接近的:

SELECT SUM(Visits) AS Visits, StatPullTime
FROM DomainStats
GROUP BY StatPullTime HAVING SUM(Visits) > 2999

2 个答案:

答案 0 :(得分:0)

以下是如何在纯SQL中执行此操作,但如果记录可以追溯到很远的话,它可能会非常低效。

SELECT a.DomainId DomainId, a.StatPullTime StatPullTime, SUM(b.Visits) Visits
FROM DomainStats a
JOIN DomainStats b ON a.DomainId = b.DomainId AND b.StatPullTime >= a.StatPullTime
GROUP BY DomainId, StatPullTime
HAVING Visits < 3000
ORDER BY DomainId, StatPullTime DESC

这很慢的原因是因为它执行O(N 2 )自连接。 @ Tomas的答案更实用。

答案 1 :(得分:0)

线性,一次通过解决方案,仅适用于MySQL(即非常高效但不符合严格的SQL):

set @sum_visits := 0, @domain_id = -1;

SELECT 
    @sum_visits := if(@domain_id = DomainId, @sum_visits, 0) + Visits AS SUM_Visits,
    @domain_id := DomainId as DomainId,
    StatPullTime,
FROM DomainStats
GROUP BY DomainId, StatPullTime
ORDER BY DomainId asc, StatPullTime desc
HAVING SUM_Visits <= 2999