SQL Server Getting error: "Cannot use aggregate functions inside of aggregate functions". Need help in SQL query

67up9zun  于 2023-06-28  发布在  其他
关注(0)|答案(1)|浏览(158)

There is a table inside SQL Server called tbl_contacts which will look similar to this screenshot (I have just highlighted few rows in yellow because those rows are going to get aggregated so that you can see difference between input and expected output):

For my requirement, I created a view for all the data manipulations. For an agent working in a team in a day, we wanted to find the avg talk time and max wait time.

I have written the following SQL query:

SELECT
    Date, agentID, teamId,
    AVG([talk time]) AS avg_talk_time,
    MAX([wait time]) AS max_wait_time
FROM
    tbl_contacts
GROUP BY
    Date, agentID, teamId

Now, I have an additional requirement to add 2 columns,

  1. The CallStart time whenever the wait time was maximum
  2. The CallEnd time whenever the wait time was maximum.

Basically, whenever max wait time occurred in a day, we want to see when the call started and when the call ended.

I tried to extend my query like this:

SELECT
    Date, agentID, teamId,
    AVG([talk time]) AS avg_talk_time,
    MAX([wait time]) AS max_wait_time,
    MAX(CASE  
            WHEN [wait time] = MAX([wait time]) 
                THEN [Call Start] 
        END) AS [Wait Time Call Start],
    MAX(CASE 
            WHEN [wait time] = MAX([wait time]) 
                THEN [Call End] 
        END) AS [Wait Time Call End]
FROM
    tbl_contacts
GROUP BY 
    Date, agentID, teamId

But I'm getting this error:

Cannot use aggregate functions inside of aggregate functions.

I need your help with this SQL query.

I just need to return these 2 columns from my query.

I'm also attaching the screenshot of the expected output below so that it is clear:

mfuanj7w

mfuanj7w1#

The error message indicates that using aggregate functions within aggregate functions is not permitted. One solution is to use your initial query as a subquery and join it to the table to obtain the related call start and call end values.

select s.*,
       [Call Start] as [Wait Time Call Start],
       [Call End] as [Wait Time Call End]
from tbl_contacts
inner join (
  Select Date, agentID, teamId, 
         AVG([talk time]) as avg_talk_time, 
         MAX([wait time]) as max_wait_time
  from tbl_contacts
  group by Date, AgentID, TeamID
) as s on s.Date = s.Date and s.agentID = t.agentID and s.teamId = t.teamId and s.max_wait_time = [wait time]

相关问题