Display records by grouping dates in MySQL

MySQLMySQLi Database

To group dates in MySQL, use the GROUP BY clause −

mysql> create table DemoTable2002
(
   CustomerName varchar(20),
   CustomerShippingDate datetime
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2002 values('Chris','2019-01-10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2002 values('David','2018-12-31');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2002 values('David','2019-12-16');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2002 values('Chris','2018-12-01');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2002;

This will produce the following output −

+--------------+----------------------+
| CustomerName | CustomerShippingDate |
+--------------+----------------------+
| Chris        | 2019-01-10 00:00:00  |
| David        | 2018-12-31 00:00:00  |
| David        | 2019-12-16 00:00:00  |
| Chris        | 2018-12-01 00:00:00  |
+--------------+----------------------+
4 rows in set (0.00 sec)

Here is the query to display records by grouping dates −

mysql> select date(min(CustomerShippingDate)),date(max(CustomerShippingDate)),CustomerName
   from DemoTable2002
   group by CustomerName;

This will produce the following output −

+---------------------------------+---------------------------------+--------------+
| date(min(CustomerShippingDate)) | date(max(CustomerShippingDate)) | CustomerName |
+---------------------------------+---------------------------------+--------------+
| 2018-12-01                      | 2019-01-10                      | Chris        |
| 2018-12-31                      | 2019-12-16                      | David        |
+---------------------------------+---------------------------------+--------------+
2 rows in set (0.00 sec)
raja
Published on 02-Jan-2020 05:42:20
Advertisements