Below is the SQL for the view that is the source of the data for the report, and also for the cross-tab control. This data deals with a service request system for our IT dept, a service request (SR), is usually a small job to address a specific problem or some smal IT job that isn’t large enough to be considered a project.
The RQST table holds these service requests, the RQST_ID field is a text field (ex: P119876), that the users use as the identifier for an SR, the unique identifier on that table is the RQST_KEY field, it is also the foreign key in the RQST_HSTRY table.
The RQST_HSTRY table holds the history of each SR as it progresses through its lifecycle, from one status to another, as people make notes, etc. We have status values (STS_VLU), which are grouped into status categories (STS_CAT). Each history record has a time in and time out value, thses are timestamps on when that record was created, the time out value of the first history record is the time in of the next history record. For example an SR is created at 03/20/2009 11:32:41am, the first status is “Requested”, that SR is updated and given a status of “Triage” at 03/21/2009 8:47:18 am, so it spent about 21 hrs and 19 min (about 0.89 days), in Requested status.
The long nested case statement is there to deal with all possible values that could be in the TIME_OUT field, that field in null until the next history record is created, so if it is null and the SR is not closed, we use getDate() because the SR is still in that status, if it is null and the SR is closed, we use the closed date timestamp because the TIME_OUT value of the very last history record will be null. I had to use seconds as the interval on these timestamp values and then divide by 86,400 to get an accurate value in days for the ‘StatusAge’.
The Summarized fields are Avg of StatusAge and Sum of StatusAge. I display the StatusAge sums for individual SRs in the detail lines and the averages of those sums at the bottom.
SELECT R.RQST_ID, RH.RQST_KEY, RH.RQST_HSTRY_KEY, RH.STS_VLU, RH.STS_CAT,
Cast(CASE WHEN RH.TIME_OUT IS NULL THEN CASE WHEN R.CLSD_DATE IS NULL THEN DATEDIFF(ss, RH.TIME_IN, getDate())
ELSE DATEDIFF(ss, RH.TIME_IN, R.CLSD_DATE) END ELSE DATEDIFF(ss, RH.TIME_IN, RH.TIME_OUT) END as Float)/86400 'StatusAge',
R.CRTE_DATE, R.CLSD_DATE
FROM dbo.RQST_HSTRY RH INNER JOIN dbo.RQST R ON RH.RQST_KEY = R.RQST_KEY
WHERE RH.STS_CAT IS NOT NULL
AND RH.STS_CAT NOT IN ('Completed', 'Waiting for Sub', 'Closed - MOB Project', 'Cancelled')