MySQL查询按时间分组

时间:2013-01-24 12:18:50

标签: mysql sql

我有一个带有字段uid(INT)和TIME(TIMESTAMP)的MySQL表,其中注册了站点上的用户登录。

在2天或更长时间内收到进入网站的用户数量最简单的方法是什么? 是否存在比我使用的片段更好的东西?

SELECT count(*) FROM
   (SELECT uid, count(*) as DistinctDayCount FROM 
       (SELECT uid, Time FROM Log GROUP BY uid, DATE(Time)) AS DistinctDays 
   GROUP BY uid) AS DaysCount
WHERE DistinctDayCount > 1

2 个答案:

答案 0 :(得分:1)

您可以使用少一个子查询来完成:

select count(*)
from (select uid, count(distinct date(time)) as DistinctDayCount
      from log
      group by uid
     ) t
WHERE DistinctDayCount > 1

说实话,不过,我会查看每个计数的数字,使用如下查询:

select DistinctDayCount, count(*), min(uid), max(uid)
from (select uid, count(distinct date(time)) as DistinctDayCount
      from log
      group by uid
     ) t
group by DistinctDayCount
order by 1

minmax给出示例用户ID,您可以进一步调查。通常在“有多少用户登录超过1天”之后的下一个问题是“他们登录的天数的分布是什么”。

答案 1 :(得分:0)

select count(*) from
(
SELECT uid, min(Time), Max(Time) 
FROM Log 
GROUP BY uid 
HAVING DATEDIFF(max(Time),min(Time))>1
) t