To GROUP BY date while using datetime, the following is the syntax −
select *from yourTableName GROUP BY date(yourColumnName);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table groupByDateDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20), -> UserPostDatetime datetime -> ); Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Larry','2018-01-02 13:45:40'); Query OK, 1 row affected (0.18 sec) mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Mike','2018-01-02 13:45:40'); Query OK, 1 row affected (0.14 sec) mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Sam','2019-01-28 12:30:34'); Query OK, 1 row affected (0.33 sec) mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('David','2019-02-10 11:35:54'); Query OK, 1 row affected (0.18 sec) mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Maxwell','2019-02-10 11:35:54'); Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from groupByDateDemo;
Here is the output −
+----+----------+---------------------+ | Id | UserName | UserPostDatetime | +----+----------+---------------------+ | 1 | Larry | 2018-01-02 13:45:40 | | 2 | Mike | 2018-01-02 13:45:40 | | 3 | Sam | 2019-01-28 12:30:34 | | 4 | David | 2019-02-10 11:35:54 | | 5 | Maxwell | 2019-02-10 11:35:54 | +----+----------+---------------------+ 5 rows in set (0.00 sec)
Let us now GROUP BY date while using datetime. The query is as follows −
mysql> select *from groupByDateDemo GROUP BY date(UserPostDatetime);
The following is the output −
+----+----------+---------------------+ | Id | UserName | UserPostDatetime | +----+----------+---------------------+ | 1 | Larry | 2018-01-02 13:45:40 | | 3 | Sam | 2019-01-28 12:30:34 | | 4 | David | 2019-02-10 11:35:54 | +----+----------+---------------------+ 3 rows in set (0.00 sec)