我是存储过程的新手,所以我可能做错了。我创建了一个存储过程,该存储过程可以带回月份名称,月份开始日期和月份结束,但是我得到了12个独立的数据集。
如何将其组合成一个?
BEGIN
SET @i = 0;
SET @start_date = "2018-09-01";
SET @end_date = LAST_DAY('2018-09-01');
WHILE @i < 12 DO
SELECT MONTHNAME(@start_date) AS month, @start_date, @end_date;
SET @i = @i + 1;
SET @start_date = DATE_ADD(@start_date, INTERVAL 1 MONTH);
SET @end_date = LAST_DAY(DATE_ADD(@end_date, INTERVAL 1 MONTH));
END WHILE;
END
答案 0 :(得分:0)
您不需要存储过程。
set @start_date = '2018-09-01';
with recursive months(m) as (
select 0
union all
select m + 1
from months
where m < 11
)
select @start_date + interval m.m month as first_day
, last_day(@start_date + interval m.m month) as last_day
from months m
order by m.m asc
结果:
first_day last_day
2018-09-01 2018-09-30
2018-10-01 2018-10-31
2018-11-01 2018-11-30
2018-12-01 2018-12-31
2019-01-01 2019-01-31
2019-02-01 2019-02-28
2019-03-01 2019-03-31
2019-04-01 2019-04-30
2019-05-01 2019-05-31
2019-06-01 2019-06-30
2019-07-01 2019-07-31
2019-08-01 2019-08-31
但是您当然也可以在SP中使用该查询。
答案 1 :(得分:0)
重写@Paul Spiegel查询,以便我了解递归查询的工作原理。
SET @start = "2018-09-01";
WITH RECURSIVE months (m)
AS (
SELECT 0
UNION ALL
SELECT m + 1
FROM months
WHERE m < 12
)
SELECT
MONTHNAME(DATE_ADD(@start, INTERVAL m MONTH)) AS month_name,
CONCAT(DATE_ADD(@start, INTERVAL m MONTH), " 00:00:00") AS start_of_month,
CONCAT(LAST_DAY(DATE_ADD(@start, INTERVAL m MONTH)), " 23:59:59") AS end_of_month
FROM months;
答案 2 :(得分:0)
对于8.0之前的MySQL版本,我们可以执行以下操作:
SELECT MONTHNAME(d.dt + INTERVAL i.n MONTH) AS month
, d.dt + INTERVAL i.n MONTH AS start_date
, LAST_DAY(d.dt + INTERVAL i.n MONTH) AS end_date
FROM ( SELECT '2018-09-01' + INTERVAL 0 MONTH AS dt ) d
CROSS
JOIN ( SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2
UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11
) i
ORDER
BY i.n