'pd.period_range(...) equivalent function in mysql
I have to generate 'yearquarter' combinations within a specific date.
example:
start_date = '2021-01-30'
end_date = '2022-05-01'
Output:
result = [ '2021Q1', '2021Q2', '2021Q3', '2021Q4', '2022Q1', '2022Q2' ]
In python we have a function which does the similar task,
pd.period_range(pd.to_datetime(stdate), pd.to_datetime(eddate), freq='Q')
Is there anything equivalent in SQL to do this, I'm using MySQL.
Solution 1:[1]
This requires MySQL 8.0 because of the common table expression:
with recursive cte (date) as (
select '2021-01-30'
union
select date + interval 3 month from cte
where date < '2022-05-01' - interval 3 month
)
select concat(year(date), 'Q', quarter(date)) as result
from cte;
Output:
+--------+
| result |
+--------+
| 2021Q1 |
| 2021Q2 |
| 2021Q3 |
| 2021Q4 |
| 2022Q1 |
| 2022Q2 |
+--------+
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bill Karwin |