简体   繁体   English

基于TIMESTAMP的MySQL分组月份

[英]MySQL grouping months based on TIMESTAMP

I have a table called user_logins which tracks user logins into the system. 我有一个名为user_logins的表,该表可跟踪用户登录系统的情况。 It has three columns, login_id, user_id, and login_time 它具有三列,login_id,user_id和login_time

login_id(INT) | user_id(INT) | login_time(TIMESTAMP)
------------------------------------------------------
  1       |      4       |   2010-6-14 08:54:36
  1       |      9       |   2010-7-16 08:56:36
  1       |      9       |   2010-8-16 08:59:19
  1       |      9       |   2010-8-16 09:00:24
  1       |      1       |   2010-8-16 09:01:24

I am looking to write a query that will determine the number of unique logins for each day and count that up for each month. 我正在寻找一个查询,该查询将确定每天的唯一登录次数,并确定每个月的唯一登录次数。 If in a day a user has logged in twice it will only be counted once. 如果一天中用户已登录两次,则只会被计算一次。 The example output would be as follows 示例输出如下

month(VARCHAR) | logins(INT)
---------------------------
 June       |     1
 July       |     1
 August     |     2

in the result table August only has 2 because the user_id 9 logged in twice in one day and him logging into the system only counts as 1 login for that day. 在结果表August中只有2个,因为user_id 9在一天之内两次登录,而他在系统中登录的那一天仅算作1次登录。

With the help of stack overflow I have written a query that achieves this but for some reason using when I am using the DATE_FORMAT function with just '%M' when trying to read in the values in java using hibernate it is causing the object to be corrupted and not recognized as a string. 在堆栈溢出的帮助下,我编写了一个查询来实现此目的,但是由于某种原因,当我尝试使用休眠方式读取Java中的值时,仅将DATE_FORMAT函数与'%M'一起使用时,会导致该对象被损坏,无法识别为字符串。 I figure it is probably because my query is doing something wrong. 我认为这可能是因为我的查询做错了什么。 My query is as follows: 我的查询如下:

 SELECT login_date, SUM(logins) as numLogins FROM (
    SELECT
      DATE_FORMAT(DATE(login_time), '%M') AS login_date,
      COUNT(DISTINCT login_id) AS logins
    FROM user_logins
    WHERE login_time > DATE_SUB(NOW() - INTERVAL 1 YEAR)
    GROUP BY DATE(login_time)) 
 AS Z GROUP BY(login_date)";

Why not use extract(month from login_time) to get the month as a numeric value? 为什么不使用extract(login_time中的month)来获取月份作为数值呢?

SELECT extract(month from login_time),
       COUNT(DISTINCT login_id) AS logins
FROM user_logins
WHERE login_time > DATE_SUB(NOW() - INTERVAL 1 YEAR)
GROUP BY extract(month from login_time)

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

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