查询查找首次输入后最近7天的条目数

时间:2016-04-04 12:26:51

标签: mysql

我有一个用户ID和时间为2列的表。时间包含创建行时的条目。我想在为该用户创建的第一个条目的7天内找到为每个用户ID创建的条目数。

+--------+----------+
|userid  |date      |
+--------+----------+
|1       | 1st Apr  |
|2       | 2nd Apr  |
|1       | 2nd Apr  |
|1       | 2nd Apr  |
|1       | 3rd Apr  |
+--------+----------+

假设我们需要从第1次开始打印2天的计数: 输出应为:

+--------+----------+
|userid  |count     |
+--------+----------+
|1       | 3        | //3 entries for 1st and 2nd Apr
|2       | 1        | //1 entry for 3rd Apr
+--------+----------+

注意:我需要在一次查询中执行此操作。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT COUNT([Date]) as count_entries, t.[user_id]
    FROM User_Time t
      WHERE [date] 
        BETWEEN 
            (SELECT MIN([date]) 
                    FROM User_Time 
                        WHERE [user_id] = t.[user_id]) 
        AND 
            (SELECT DATEADD(DAY, 7, MIN([date])) 
                 FROM User_Time 
                       WHERE [user_id] = t.[user_id])
    GROUP BY [user_id]

很抱歉,我目前没有MySQL,但我希望你能适应它,将DATEADD更改为DATE_ADD。