SELECT
A.EnterpriseName,
aed.SkillTargetID,
A.PeripheralNumber,
aed.LoginDateTime,
Event = CASE Event WHEN 1 THEN 'Login (1)' WHEN 2 THEN 'Logout(2)' WHEN 3 THEN 'NotReady (3)' END ,
EventStart = DATEADD(ss,-Duration,DateTime),
EventEnd = DateTime,
aed.Duration,
Reason = rc.ReasonText + '(' + CONVERT(varchar(10),rc.ReasonCode) + ')',
aed.ReasonCode
FROM Agent_Event_Detail aed
LEFT OUTER JOIN Reason_Code rc on aed.ReasonCode = rc.ReasonCode
JOIN Agent A on aed.SkillTargetID = A.SkillTargetID
WHERE aed.SkillTargetID = :AgentSkillTargetID
and aed.DateTime >= :startDate
and aed.DateTime < :endDate
order by DateTime,Reason