0

我有一个用户登录表,我想找到在 5 天内登录该站点超过 3 次的用户。

例如我的表是:

id | user_id | login_date 
---+---------+--------------
 1 |    10   | 10.1.2014 00:00
 2 |    10   | 11.1.2014 10:10
 3 |    12   | 11.1.2014 11:00
 4 |    10   | 11.1.2014 12:00
 5 |    12   | 12.1.2014 00:00
 6 |    10   | 13.1.2014 10:00
 7 |    12   | 18.1.2014 00:00
 8 |    12   | 22.1.2014 09:00

对于这个示例表,我想选择 user_id 10,因为他/她在 5 天内登录超过 3 次。

你能帮我吗?

编辑:我忘了提到数据库是 sql server 2008

4

3 回答 3

1

如果您使用的是 SQL Server 2012+,则可以使用LEAD窗口函数计算任意 3 条连续记录之间的天数差异:

select distinct USER_ID
from (
select USER_ID, 
       datediff(d, login_date,
                   LEAD(login_date, 2) OVER (PARTITION BY user_id 
                                             ORDER BY login_date)) as diffDates
from users ) t
where t.diffDates <= 5

然后只需选择USER_IDs天数差异等于或小于 5 的那些。

SQL 小提琴演示

如果您使用的是 SQL Server 2008 或 2005,那么您可以ROW_NUMBER结合使用自连接来模拟LEAD功能:

;WITH CTE AS (
   SELECT id, user_id, login_date,
          ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS rn
   FROM users
) 
SELECT DISTINCT user_id
FROM (             
   SELECT c1.user_id, 
          DATEDIFF(d, c1.login_date, c2.login_date) AS diffInDays
   FROM CTE AS c1
   INNER JOIN CTE AS c2 ON c1.user_id = c2.user_id AND c1.rn = c2.rn - 2
  ) t
WHERE t.diffInDays <= 5

diffInDays在上述查询中,本质上是任意 3 次连续用户登录之间的滚动天数差异。

SQL 小提琴演示

于 2015-04-20T14:33:52.473 回答
1

您可以通过自行加入在它加入的记录后 5 天内的记录user_id所在的表来做到这一点,如下所示:JOIN

CREATE TABLE #login
    (
      id INT ,
      user_id INT ,
      login_date DATETIME
    )

INSERT  INTO #login
        ( id, user_id, login_date )
VALUES  ( 1, 10, '2014-01-10 00:00' ),
        ( 2, 10, '2014-01-11 10:10' ),
        ( 3, 12, '2014-01-11 11:00' ),
        ( 4, 10, '2014-01-11 12:00' ),
        ( 5, 12, '2014-01-12 00:00' ),
        ( 6, 10, '2014-01-13 10:00' ),
        ( 7, 12, '2014-01-18 00:00' ),
        ( 8, 12, '2014-01-22 09:00' )

SELECT  t1.user_id ,
        t1.login_date AS FirstDateInLoginPeriod ,
        COUNT(t2.user_id) AS LoginCount
FROM    #login t1
        INNER JOIN #login t2 ON t2.user_id = t1.user_id
                  AND t2.login_date 
                      BETWEEN t1.login_date AND DATEADD(DAY, 5, t1.login_date)
GROUP BY t1.user_id ,
        t1.login_date
HAVING  COUNT(t2.user_id) > 3

DROP TABLE #login

产生:

user_id  FirstDateInLoginPeriod     LoginCount
----------------------------------------------
10       2014-01-10 00:00:00.000    4
于 2015-04-20T14:41:58.270 回答
0

You can use following query to get your result.

As you can see you can use DATEADD function for calculating reference date and use having to filter logins count to be more or equal 3

Select count(*),user_id 
from table_name 
where login_date>=DATEADD (day,-5,GETDATE())
group by user_id  
having COUNT(*) >=3
于 2015-04-20T14:36:41.517 回答