'Show Cost Data by Month based on Date Range

I have an existing table (jobCost) that has cost data by type and month as shown in the example here.

Job Month Material Labor Equip
123 01/1/22 50.00 25.00 75.00
123 02/1/22 20.00 45.00 60.00
123 03/1/22 10.00 35.00 25.00

I have an existing table (jobDetails) that contains the job start and end date (for example start 12/15/2021 and end 5/15/2022).

I want to create a table that shows one row for each month in the date range and then provides the total cost for each month as shown here.

Month Cost
12/21 0
01/22 150.00
02/22 125.00
03/22 70.00
04/22 0
05/22 0

I found the query below which will successfully convert my job start and end dates to rows, but I don't know how to have the datetime in the declare statement read from my existing data (as the dates are different for each job). If I can figure that out, then I can join the cost data to this by month.


DECLARE @StartDate datetime = '12/15/2021'
       ,@EndDate   datetime = '5/15/2022'
;

WITH theDates AS
     (SELECT @StartDate as theDate
      UNION ALL
      SELECT DATEADD(day, 1, theDate)
        FROM theDates
       WHERE DATEADD(day, 1, theDate) <= @EndDate
     )
SELECT theDate as theValue
  FROM theDates
OPTION (MAXRECURSION 0)

Here is the Job details sample table and query.

Job Start End
123 12/3/2021 05/30/2022
SELECT
    Job
    ,StartDate
    ,EndDate
FROM 
    JobDetails

Here is the query for the job cost

SELECT 
    jc.Month
    ,CASE WHEN ct.Category = 'L' THEN SUM(jc.Cost) END as LaborCost
    ,CASE WHEN ct.Category = 'E' THEN SUM(jc.Cost) END as EquipmentCost
    ,CASE WHEN ct.Category = 'M' THEN SUM(jc.Cost) END as MaterialCost

FROM
    JobCost jc
    INNER JOIN CostCategory ct ON jc.Group = ct.Group AND jc.CostType = ct.CostType

GROUP BY
    jc.Month
sql


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source