Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

How to count active jobs at the end of each month across a period of time Expand / Collapse
Author
Message
Posted Sunday, May 19, 2013 6:19 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, April 02, 2014 9:02 PM
Points: 4, Visits: 119
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:

Date Active jobs
20120131 2
20120229 2
20120331 5
20120430 4
20120531 3
20120630 2

A job can be counted multiple times depending on when it was received and finished. Any advice would be appreciated. Thanks.
Post #1454382
Posted Sunday, May 19, 2013 11:54 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, April 02, 2014 9:02 PM
Points: 4, Visits: 119
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?
Post #1454406
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse