1

I have a table [T] with columns id,start_date, end_date. I want to get id, date, where id is split into multiple dates using start date and end date. For example: Input:

id start_date end_date
1 2022-04-03 2022-04-07
2 2022-04-11 2022-04-11

Expected Output

id date
1 2022-04-03
1 2022-04-04
1 2022-04-05
1 2022-04-06
1 2022-04-07
2 2022-04-11
3
  • 1
    What version of MySQL? Commented Apr 25, 2022 at 16:40
  • The version is MySQL 8 Commented Apr 26, 2022 at 1:21
  • You can use a recursive Common Table expression to create a domain of dates. Use min(start_date) as the base case for the recursion och increment until max(end_date). Then join this with your table using the between predicate Commented Jul 7, 2023 at 18:58

2 Answers 2

0

Build a dates table with all possible dates.

INSERT INTO OutputTable (t_id, date)
    SELECT T.id, d.date
        FROM T
        JOIN dates AS d
        WHERE d.date BETWEEN T.start_date AND T.end_date;

(By convention id is assumed to be the PRIMARY KEY, hence unique, for a table. So, I changed to t_id for your output.)

0

You can try this (I have used MySQL version 8.0.34):

CREATE TABLE t (
  id INT NOT NULL,
  start DATE NOT NULL,
  end DATE NOT NULL
);

INSERT INTO t (id, start, end)
  VALUES 
    (1, '2022-04-03', '2022-04-07'), 
    (2, '2022-04-11', '2022-04-11'),
    (3, '2022-05-12', '2022-05-13');

WITH RECURSIVE t_result (id, start) AS
(
  SELECT id, start 
    FROM t
  UNION ALL
  SELECT id, start + INTERVAL 1 DAY 
    FROM t_result
    WHERE start + INTERVAL 1 DAY <= (SELECT end FROM t WHERE t.id = t_result.id)
)
SELECT id, start AS date 
  FROM t_result 
  ORDER BY id, date;

The output from the query:

+------+------------+
| id   | date       |
+------+------------+
|    1 | 2022-04-03 |
|    1 | 2022-04-04 |
|    1 | 2022-04-05 |
|    1 | 2022-04-06 |
|    1 | 2022-04-07 |
|    2 | 2022-04-11 |
|    3 | 2022-05-12 |
|    3 | 2022-05-13 |
+------+------------+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.