Link to home
Start Free TrialLog in
Avatar of angel7170
angel7170Flag for United States of America

asked on

Stored Procedure in SQL Server 2008

Hello Experts,

I'm having trouble in writing a procedure to calculate "Work Time" for each ticket that is resolved in Help Desk environment. This work time should not calculate the time when a ticket is in "Pending" status.

This is the table structure with the data

TicketNo    Status             Datetime
TK123       TicketOpen      03/22/2011  7:00AM
TK123       To - Pending   03/22/2011 8:00AM
TK123       To - Open        03/22/2011 9:30AM
TK123       To-Pending        03/22/2011 10:00AM
TK123       To-Open           03/22/2011  10:45AM
TK123      To-Closure        03/22/2011   11:30AM

So actual work time should be 2 hours and 15 Minutes excluding Pending Hours ( Time when the ticket went to "To-Pending" and came out to "To-Open" status) which is 1 Hour and 15 Minutes.

How can I write a Procedure to do this calculate? Please assist.

Thank you very much
ASKER CERTIFIED SOLUTION
Avatar of Christopher Gordon
Christopher Gordon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Raja Jegan R
This should do and use it in a procedure if required:
select TicketNo, cast(cast(135/60 as varchar(10)) + ':' + cast(135%60 as varchar(10)) as time)
FROM 
(
select t1.TicketNo, t1.Status old_status, t2.Status new_status, DATEDIFF(mi, t1.Datetime, t2.Datetime) time_value
from ur_table_name t1
left join ur_table_name t2 on t1.TicketNo = t2.TicketNo and t1.rnum = t2.rnum - 1
Where t1.Status <> 'Pending' ) temp
GROUP BY TicketNo

-- Tested with your sample input

;with cte as (
SELECT TicketNo, Status, Datetime, ROW_NUMBER() over ( PARTITION BY TicketNo order by Datetime) rnum
FROM (
SELECT 'TK123' TicketNo, 'Open' Status,  cast('2011-03-22 7:00:00' as datetime) Datetime
union all
SELECT 'TK123', 'Pending',  cast('2011-03-22 8:00:00' as datetime)
union all
SELECT 'TK123', 'Open',  cast('2011-03-22 9:30:00' as datetime)
union all
SELECT 'TK123', 'Pending',  cast('2011-03-22 10:00:00' as datetime)
union all
SELECT 'TK123', 'Open',  cast('2011-03-22 10:45:00' as datetime)
union all
SELECT 'TK123', 'Closure',  cast('2011-03-22 11:30:00' as datetime)
)temp
)
select TicketNo, cast(cast(135/60 as varchar(10)) + ':' + cast(135%60 as varchar(10)) as time)
FROM 
(
select t1.TicketNo, t1.Status old_status, t2.Status new_status, DATEDIFF(mi, t1.Datetime, t2.Datetime) time_value
from cte t1
left join cte t2 on t1.TicketNo = t2.TicketNo and t1.rnum = t2.rnum - 1
Where t1.Status <> 'Pending' ) temp
GROUP BY TicketNo

Open in new window

Avatar of angel7170

ASKER

Thank you both.

I tried gohord solution and it works as expected. Thanks