tags:

views:

11

answers:

1

I have a table called user_logins which tracks user logins into the system. It has three columns, login_id, user_id, and 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.

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. 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)";
A: 

Why not use extract(month from login_time) to get the month as a numeric value?

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)
a_horse_with_no_name
that gives me a syntax error, I was not aware of the extract method.
IamBanksy
Works for me with MySQL 5.0
a_horse_with_no_name