May 19, 2013 at 6:19 pm
My apologies if this question has been answered elsewhere but I can’t find a solution. I need to count the number of active jobs that exist at the end of each month. A job is active if it has been received but not yet finished. The data looks like this:
CREATE TABLE #Files
(Job NVARCHAR(10), Received DATETIME, Finished DATETIME)
INSERT INTO #Files (JOB, Received, Finished)
SELECT 'A1', CAST('20120110' AS DATETIME), CAST('20120506' AS DATETIME) UNION ALL
SELECT 'A23', CAST('20120113' AS DATETIME), NULL UNION ALL
SELECT 'B4', CAST('20120221' AS DATETIME), CAST('20120224' AS DATETIME) UNION ALL
SELECT 'L5', CAST('20120307' AS DATETIME), CAST('20120425' AS DATETIME) UNION ALL
SELECT 'D5', CAST('20120316' AS DATETIME), NULL UNION ALL
SELECT 'S3', CAST('20120323' AS DATETIME), CAST('20120510' AS DATETIME) UNION ALL
SELECT 'D2', CAST('20120502' AS DATETIME), CAST('20120607' AS DATETIME)
SELECT * FROM #Files ORDER BY 2, 3
DROP TABLE #Files
So, from the data above, I need to calculate the following:
DateActive jobs
201201312
201202292
201203315
201204304
201205313
201206302
A job can be counted multiple times depending on when it was received and finished. Any advice would be appreciated. Thanks.
May 19, 2013 at 11:54 pm
I think I may have found a solution. It's all in the joins. I created a recursive CTE to generate a framework of end-of-month dates covering the period of time required for the report. I then linked the job data back to the list of dates like this:
SELECT CTEdates.EndofMonth, COUNT(Job)
FROM CTEDates
LEFT OUTER JOIN #Files ON #Files.Received <= CTEDates.EndofMonth
AND ( #Files.Finished IS NULL OR #Files.Finished > CTEDates.EndofMonth )
GROUP BY CTEdates.EndofMonth
Does that make sense or is there a more efficient way of writing the query?
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply