admin

如何突破每个月的日期范围

sql

我是SQL的初学者。互联网上有很多资源,但我无法实现。假设我有这样的一行:

日期格式为“ YYYY-MM-DD”:

+---------+--------------+------------+------------+
| name    | course       | sdate      | edate      |
+---------+--------------+------------+------------+
| Tanzeel | SQL Bootcamp | 2019-05-28 | 2019-11-20 |
+---------+--------------+------------+------------+

基本上这就是说 Tanzeel2019年5月2019 11月 参加了 SQL Bootcamp
。(日期/日期在这里无关紧要)。我想像这样分解这个范围:

+---------+--------------+------------+
| name    | course       | enrollMonth|
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-05    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-06    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-07    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-08    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-09    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-10    |
+---------+--------------+------------+
| Tanzeel | SQL Bootcamp | 2019-11    |
+---------+--------------+------------+

正确的方法是什么?请帮我。我的版本是:

+--------------------------+-------------------------------+
| Variable_name            | Value                         |
+--------------------------+-------------------------------+
| admin_tls_version        | TLSv1,TLSv1.1,TLSv1.2,TLSv1.3 |
| immediate_server_version | 999999                        |
| innodb_version           | 8.0.21                        |
| original_server_version  | 999999                        |
| protocol_version         | 10                            |
| slave_type_conversions   |                               |
| tls_version              | TLSv1,TLSv1.1,TLSv1.2,TLSv1.3 |
| version                  | 8.0.21                        |
| version_comment          | MySQL Community Server - GPL  |
| version_compile_machine  | x86_64                        |
| version_compile_os       | Win64                         |
| version_compile_zlib     | 1.2.11                        |
+--------------------------+-------------------------------+

阅读 150

收藏
2021-07-01

共1个答案

admin

用递归CTE

with recursive cte as (
  select name, course, sdate, edate 
  from tablename
  union all
  select name, course, sdate + interval 1 month, edate
  from cte 
  where last_day(sdate) < edate
)
select name, course, date_format(sdate, '%Y-%m') enrollMonth
from cte

参见演示
结果:

> name    | course       | enrollMonth
> :------ | :----------- | :----------
> Tanzeel | SQL Bootcamp | 2019-05    
> Tanzeel | SQL Bootcamp | 2019-06    
> Tanzeel | SQL Bootcamp | 2019-07    
> Tanzeel | SQL Bootcamp | 2019-08    
> Tanzeel | SQL Bootcamp | 2019-09    
> Tanzeel | SQL Bootcamp | 2019-10    
> Tanzeel | SQL Bootcamp | 2019-11
2021-07-01