WITH JobPositions AS (
SELECT 'Job1' AS JobName, 3 AS Positions
UNION ALL
SELECT 'Job2', 4 AS Positions
)
,Workers AS (
SELECT 'Worker1' AS WorkerName, 'Job1' AS JobName
UNION ALL
SELECT 'Worker2' AS WorkerName, 'Job1' AS JobName
UNION ALL
SELECT 'Worker3' AS WorkerName, 'Job2' AS JobName
)
-- Real query starts here.
-- Create a line for each position in each job
, JobPositionNumber AS (
SELECT JobName, Positions, 1 AS PositionNumber
FROM JobPositions
UNION ALL
SELECT JobName, Positions, PositionNumber + 1
FROM JobPositionNumber
WHERE PositionNumber < Positions
)
-- Number the workers from 1 and up per job
, WorkerPositionNumber AS (
SELECT WorkerName
,JobName
,ROW_NUMBER() OVER (PARTITION BY JobName
ORDER BY WorkerName) AS PositionNumber
FROM Workers
)
-- Now just join numbered jobs with numbered workers
SELECT JobPositionNumber.JobName
,CASE WHEN WorkerPositionNumber.WorkerName IS NULL
THEN '--- empty place ---'
ELSE WorkerName
END AS WorkerName
FROM JobPositionNumber
LEFT JOIN WorkerPositionNumber
ON JobPositionNumber.JobName = WorkerPositionNumber.JobName
AND JobPositionNumber.PositionNumber = WorkerPositionNumber.PositionNumber
ORDER BY JobPositionNumber.JobName
,JobPositionNumber.PositionNumber