We have Incidents in our system with Start Time and Finish Time and project name (and other info) .
We would like to have report: How many Incidents has ‘open’ status per month per project.
Open status mean: Not finished.
If incident is created in December 2009 and closed in March 2010, then it should be included in December 2009, January and February of 2010.
Needed structure should be like this:
Project Year Month Count
------- ------ ------- -------
Test 2009 December 2
Test 2010 January 10
Test 2010 February 12
....
In SQL Server:
Briefly, how it works:
The most inner subselect, that works directly on the Incidents table, simply kind of ‘normalises’ the table (replaces NULL finish times with the current time) and adds a month difference column,
MonthDiff. If there can be no NULLs in your case, just remove theISNULLexpression accordingly.The outer subselect uses
MonthDiffto break up the time range into a series of timestamps corresponding to the months where the incident was still open, i.e. the FinishTime month is not included. A system table calledmaster..spt_valuesis also employed there as a ready-made numbers table.Lastly, the main select is only left with the task of grouping the data.