SELECT te.[AssignedAgent] AS [AgentName],
       COUNT(1)                                                        AS [TaskCount],
       AVG(CASE
               WHEN te.[StartedAt] IS NOT NULL AND te.[FinishedAt] IS NOT NULL
                   THEN CAST(DATEDIFF(SECOND, te.[StartedAt], te.[FinishedAt]) AS FLOAT)
           END)                                                        AS [AverageDurationSeconds],
       SUM(CASE WHEN te.[Status] = @CompletedStatus THEN 1 ELSE 0 END) AS [SuccessCount],
       SUM(CASE WHEN te.[Status] = @FailedStatus THEN 1 ELSE 0 END)    AS [FailureCount]
FROM [dbo].[TaskExecutions] te
WHERE te.[AssignedAgent] IS NOT NULL
  AND (@AgentName IS NULL
   OR te.[AssignedAgent] = @AgentName)
  AND (@Status IS NULL
   OR te.[Status] = @Status)
  AND (@StartDate IS NULL
   OR te.[QueuedAt] >= @StartDate)
  AND (@EndDate IS NULL
   OR te.[QueuedAt] <= @EndDate)
GROUP BY te.[AssignedAgent]
ORDER BY te.[AssignedAgent];
