MySQL query to group data in the form of user login time per hour and get the records of the users logged in the recent hour?

MySQLMySQLi Database

You can use a subquery with JOIN condition for this. The syntax is as follows −

SELECT yourTablevariableName.*
FROM
(
   SELECT MAX(UNIX_TIMESTAMP(yourDateTimeColumnName)) AS anyAliasName
   FROM getLatestHour
   GROUP BY HOUR(UserLoginDateTime)
) yourOuterVariableName
JOIN yourTableName yourTablevariableName
ON UNIX_TIMESTAMP(yourDateTimeColumnName) = yourOuterVariableName.yourAliasName
WHERE DATE(yourDateTimeColumnName) = 'yourDateValue';

To understand the above syntax and the result to be achieved, let us create a table. The query to create a table is as follows −

mysql> create table getLatestHour
   -> (
   -> UserId int,
   -> UserName varchar(20),
   -> UserLoginDateTime datetime
   -> );
Query OK, 0 rows affected (0.68 sec)

Now you can insert some records in the table using insert command. The records are the user records including the user login date and time. The query is as follows −

mysql> insert into getLatestHour values(100,'John','2019-02-04 10:55:51');
Query OK, 1 row affected (0.27 sec)
mysql> insert into getLatestHour values(101,'Larry','2019-02-04 12:30:40');
Query OK, 1 row affected (0.16 sec)
mysql> insert into getLatestHour values(102,'Carol','2019-02-04 12:40:46');
Query OK, 1 row affected (0.20 sec)
mysql> insert into getLatestHour values(103,'David','2019-02-04 12:44:54');
Query OK, 1 row affected (0.17 sec)
mysql> insert into getLatestHour values(104,'Bob','2019-02-04 12:47:59');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from getLatestHour;

The following is the output −

+--------+----------+---------------------+
| UserId | UserName | UserLoginDateTime   |
+--------+----------+---------------------+
|    100 | John     | 2019-02-04 10:55:51 |
|    101 | Larry    | 2019-02-04 12:30:40 |
|    102 | Carol    | 2019-02-04 12:40:46 |
|    103 | David    | 2019-02-04 12:44:54 |
|    104 | Bob      | 2019-02-04 12:47:59 |
+--------+----------+---------------------+
5 rows in set (0.00 sec)

Here is the query to group data per hour and get the record of the recent hour. The query is as follows −

mysql> SELECT tbl1.*
   -> FROM (
   -> SELECT MAX(UNIX_TIMESTAMP(UserLoginDateTime)) AS m1
   -> FROM getLatestHour
   -> GROUP BY HOUR(UserLoginDateTime)
   -> ) var1
   -> JOIN getLatestHour tbl1
   -> ON UNIX_TIMESTAMP(UserLoginDateTime) = var1.m1
   -> WHERE DATE(UserLoginDateTime) = '2019-02-04';

The following is the output −

+--------+----------+---------------------+
| UserId | UserName | UserLoginDateTime   |
+--------+----------+---------------------+
|    100 | John     | 2019-02-04 10:55:51 |
|    104 | Bob      | 2019-02-04 12:47:59 |
+--------+----------+---------------------+
2 rows in set (0.05 sec)
raja
Updated on 30-Jul-2019 22:30:24

Advertisements