I have these two tables linked by a simple key, one contains the project name and its start date and the other the planning, which look something like this:
projects
ID NAME START_DATE
1 foo 01/01/2017
2 barr 01/02/2017
planning
PRJ M0 M1 M2
1 70 75 80
2 50 60 70
Could someone help me to join these two tables in order to produce:
PRJ DATE PLAN
1 01/01/2017 70
1 01/02/2017 75
1 01/03/2017 80
2 01/02/2017 50
2 01/03/2017 60
2 01/04/2017 70
unpivot
seems to be useful here, but I haven't got much practice with it.
thanks
Consider running an UNPIVOT
in a CTE. Then, in main query calculate a row number to which can be used to add days to START_DATE.
Also, consider not storing data in a wide format with M*
columns but long format of original value and indicator columns. Otherwise queries like below will be complex.
WITH master AS
(SELECT *
FROM planning
UNPIVOT ("PLAN" FOR M_COLS IN (M0, M1, M2)) -- BUILD OUT LIST IN APP CODE
)
SELECT m.PRJ, p.START_DATE + m.row_num AS m."DATE", m."PLAN"
FROM projects p
INNER JOIN
(SELECT PRJ, "PLAN", ROW_NUMBER()
OVER (PARTITION BY PRJ ORDER BY PRJ) - 1 AS row_num
FROM master) AS m
ON p.ID = m.PRJ;