在MySQL中按日期分组显示记录

要在MySQL中对日期进行分组,请使用GROUP BY子句-

mysql> create table DemoTable2002

(

   CustomerName varchar(20),

   CustomerShippingDate datetime

);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable2002 values('Chris','2019-01-10');

mysql> insert into DemoTable2002 values('David','2018-12-31');

mysql> insert into DemoTable2002 values('David','2019-12-16');

mysql> insert into DemoTable2002 values('Chris','2018-12-01');

使用select语句显示表中的所有记录-

mysql> select * from DemoTable2002;

这将产生以下输出-

+--------------+----------------------+

| 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)

这是通过按日期分组显示记录的查询-

mysql> select date(min(CustomerShippingDate)),date(max(CustomerShippingDate)),CustomerName

   from DemoTable2002

   group by CustomerName;

这将产生以下输出-

+---------------------------------+---------------------------------+--------------+

| 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)

以上是 在MySQL中按日期分组显示记录 的全部内容, 来源链接: utcz.com/z/341006.html

回到顶部