Question

I have a mySQL table with the next contents:

 ID   START        FREQUENCY  REPETITIONS  RESOURCE 
 --------------------------------------------------
 1    24/02/2014   daily      5            10
 2    24/02/2014   yearly     2            11

Is there any easy way to transform this into a view such as:

ID  DATE         RESOURCE
-------------------------
1   24/02/2014   10
1   25/02/2014   10
1   26/02/2014   10
1   27/02/2014   10
1   28/02/2014   10
2   24/02/2014   11
2   24/02/2015   11

Thanks

Was it helpful?

Solution

If you can have a limited number of repetitions, you can create a Numbers table like this:

CREATE TABLE numbers (
  num INT,
  i INT
);

INSERT INTO numbers VALUES
(1,1),
(2,1),
(2,2),
(3,1),
(3,2),
(3,3),
(4,1),
(4,2),
(4,3),
(4,4),
...

then you can use a JOIN:

SELECT
  ID,
  `START` + INTERVAL CASE WHEN FREQUENCY='daily' THEN i-1 ELSE 0 END DAY
          + INTERVAL CASE WHEN FREQUENCY='yearly' THEN i-1 ELSE 0 END YEAR
   as `Date`,
  RESOURCE
FROM
  yourtable INNER JOIN numbers
  ON yourtable.REPETITIONS = numbers.num
ORDER BY
  ID, numbers.i

Please see fiddle here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top