简体   繁体   English

日期范围内每位用户每天的登录次数

[英]Number of logins per user per day in a date range

I saw many posts around that area, but couldn't find the exact one. 我在该地区看到了很多帖子,但找不到确切的帖子。 I have a table that registers all of users logins to my app and it contains two columns - userID and timeOfLogin. 我有一个表,用于注册所有登录到我的应用程序的用户,它包含两列-userID和timeOfLogin。 It looks like that: 看起来像这样:

userID, timeOfLogin
1     , 14-01-10 00:07:38
2     , 14-01-10 01:28:45
3     , 14-01-10 01:28:45
1     , 14-01-09 02:04:08
1     , 14-01-09 06:14:54
etc....

I want to have a table that counts the number of unique user logins per day since a specific "day1" that I define in the query (day2 is the following day and so on). 我想要一个表,该表计算自从我在查询中定义的特定“ day1”(day2是第二天,依此类推)以来,每天的唯一用户登录次数。 The table should look something like: 该表应如下所示:

userID, numOFLogins day1, numOfLogins Day2, numOfLogins Day3, ...., numOfLogins DayN
1     ,      10         , 12              , 0               , ...., 12
2     ,      3          , 6               , 7               , ...., 15
132   ,      0          , 5               , 9               , ...., 14

You can do this with conditional aggregation: 您可以使用条件聚合来做到这一点:

select userId,
       sum(date(timeOfLogin) = date(@day1)) as NumLogins_0,
       sum(date(timeOfLogin) = date(date(@day1) + 1)) as NumLogins_1,
       sum(date(timeOfLogin) = date(date(@day1) + 2)) as NumLogins_2,
       sum(date(timeOfLogin) = date(date(@day1) + 3)) as NumLogins_3,
       sum(date(timeOfLogin) = date(date(@day1) + 4)) as NumLogins_4
from table t
group by userId;

In MySQL, date(timeOfLogin) = @day1 is treated as a 0 when the expression is false and 1 when it is true. 在MySQL中,当表达式为false时, date(timeOfLogin) = @day1被视为0 ,而为true则被视为1

I'm just using @day1 to represent your variable for the date, whatever that is. 我只是用@day1代表日期的变量,不管是什么。

This will work for a fixed number of columns (such as the 5 days shown above). 这适用于固定数量的列(例如上面显示的5天)。 If you want a variable number of columns, then you cannot do this with a simple SQL statement. 如果您想要可变数量的列,则无法使用简单的SQL语句执行此操作。 You will need to construct the SQL in a string, use prepare , and execute it. 您将需要在字符串中构造SQL,使用prepare并执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM