计算所有用户的登录天数

时间:2016-02-19 09:47:47

标签: mysql

假设我有一个mysql表,其中包含每个用户的登录时间:

"eventDate"    "eventTime"              "name"
"2016-02-06"   "2016-02-06 01:01:01"    "nameA"
"2016-02-06"   "2016-02-06 05:04:20"    "nameA"
"2016-02-06"   "2016-02-06 06:01:18"    "nameC"
"2016-02-07"   "2016-02-07 03:04:43"    "nameA"
"2016-02-07"   "2016-02-07 08:09:23"    "nameB"
"2016-02-07"   "2016-02-07 09:09:23"    "nameB"
"2016-02-07"   "2016-02-07 10:09:23"    "nameB"
"2016-02-07"   "2016-02-07 11:09:23"    "nameB"

每当用户登录时,我的服务器都会在此表中添加一条新记录。

如何计算所有用户的登录天数?

这是我想要的结果:

"name"      "times"
"nameA"     2
"nameB"     1
"nameC"     1

如果用户在一天内多次登录,则只计算其中一条记录。

以下是我解决这个问题的计划;但是我在第一步陷入困境。

创建一个删除了重复日期的临时视图。

"eventDate"     "eventTime"     "name"
"2016-02-06"    "2016-02-06 01:01:01"   "nameA"
"2016-02-06"    "2016-02-06 06:01:18"   "nameC"
"2016-02-07"    "2016-02-07 03:04:43"   "nameA"
"2016-02-07"    "2016-02-07 08:09:23"   "nameB"

然后我就能用

做我想做的事

select name, count(name) from myDB.loginTable where eventTime between '2016-02-06 00:00:00' and '2016-02-07 23:59:59' group by name;

3 个答案:

答案 0 :(得分:1)

只需COUNT DISTINCT时间并按名称分组:

SELECT
    name,
    COUNT(DISTINCT DATE(eventTime)) times
FROM
    login_table
GROUP BY
    name

或直接使用eventDate列:

SELECT
    name,
    COUNT(DISTINCT eventDate) times
FROM
    login_table
GROUP BY
    name

答案 1 :(得分:0)

我可能会使用子查询 - 首先获取每个用户的不同日期\月\年,然后计算出现次数,如下所示:

SELECT COUNT(name) 
FROM (
    SELECT DISTINCT DATE(eventTime), name 
    FROM loginTable
) 
GROUP BY name

答案 2 :(得分:0)



Any