Search code examples
mysqlsqlrdsamazon-aurora

MySQL how to split a date into known intervals and transform it in rows?


How do I split a selected date value into many rows, with as a known interval until now for example? I could do it using Recursive CTE, but MySql Aurora(RDS) does't give support.

eg: taking a single result like

|--|----------|
|id|createdAt |
|--|----------|
|1 |2018-01-01|
|--|----------|

Given a 7 days interval, the query should output data like:

|----------|
|clycles   |
|----------|
|2018-01-01|
|2018-01-08|
|2018-01-15|
|2018-01-22|
|...       |
|----------|

Solution

  • If you have a (possibly temporary) table of all possible dates in a column d, you can

    SELECT whatever, d FROM somewhere 
    JOIN dates 
    WHERE d BETWEEN createdAt AND CURRENT_DATE() 
    AND MOD(DATEDIFF(d, createdAt),7)=0
    

    See also How to populate a table with a range of dates?