P粉9249157872023-08-29 11:21:21
將數字範圍
移至自己的CTE中以分離事物,我們現在有一個包含80個數字的大列表(可能更大)。
然後我們找到開始/結束之間的月數,並連接相同數量的行。然後進行數學計算,將範圍轉換為選擇部分:
WITH range_of_numbers AS ( SELECT row_number() OVER (ORDER BY SEQ4())-1 AS rn FROM TABLE(GENERATOR(rowcount=>80)) ) SELECT t1.name, t1.int_value, t1.start, t1.end, DATEADD(MONTH, r.rn, t1.start) as interval FROM table1 AS t1 JOIN range_of_numbers as r ON date_diff('month', t1.START, t1.end) <= between r.rn ORDER BY 2,1,3;
另一個選擇是建立一個長時間範圍的日期表
CREATE TABLE dates AS SELECT DATEADD(MONTH, row_number() OVER (ORDER BY SEQ4())-1, '1980-01-01') as month_date FROM TABLE(GENERATOR(rowcount=>8000))
然後我們使用BETWEEN來取得(開始,結束)範圍內的包含值,變成:
FROM table1 AS t1 JOIN dates as d ON d.month_date BETWEEN t1.START AND t1.end
P粉5671123912023-08-29 00:50:09
WITH RECURSIVE cte AS ( SELECT name, int_value, start, `end`, 1 rownum, DATE_FORMAT(start, '%m-%Y') `interval` FROM source_table UNION ALL SELECT name, int_value, start, `end`, 1 + rownum, DATE_FORMAT(start + INTERVAL rownum MONTH, '%m-%Y') FROM cte WHERE start + INTERVAL rownum - 1 MONTH < `end` ) SELECT name, int_value, start, `end`, `interval` FROM cte ORDER BY rownum;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bdd028a7755fdcb8296df2301baeb295
如果您不需要月份前導零,請使用'%c-%Y'
模式。