0

我有一张表格,用于存储不同网站的每日指标。表格示例:

域统计

|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
4

2 回答 2

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
于 2013-06-27T18:50:39.973 回答
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 的回答更实用。

于 2013-06-27T18:50:00.630 回答