title: AVG or SUM in SQL where the values are being calculated on the fly
body: <p>I have an existing SQL query that gets call stats from a Zultys MX250 phone system: -</p>
  
  <pre><code>SELECT
      CONCAT(LEFT(u.firstname,1),LEFT(u.lastname,1)) AS Name,
      sec_to_time(SUM(
          time_to_sec(s.disconnecttimestamp) - time_to_sec(s.connecttimestamp)
      )) AS Duration,
      COUNT(*) AS '#Calls'
  FROM
      session s
      JOIN mxuser u ON
          s.ExtensionID1 = u.ExtensionId
          OR s.ExtensionID2 = u.ExtensionId
  WHERE
      s.ServiceExtension1 IS NULL
      AND s.connecttimestamp &gt;= CURRENT_DATE
      AND BINARY u.userprofilename = BINARY 'DBAM'
  GROUP BY
      u.firstname,
      u.lastname
  ORDER BY
      '#Calls' DESC,
      Duration DESC;
  </code></pre>
  
  <p>Output is as follows: -</p>
  
  <pre>
  Name    Duration        #Calls
  TH      01:19:10        30
  AS      00:44:59        28
  EW      00:51:13        22
  SH      00:21:20        13
  MG      00:12:04        8
  TS      00:42:02        5
  DS      00:00:12        1
  </pre>
  
  <p>I am trying to generate a 4th column that shows the average call time for each user, but am struggling to figure out how.</p>
  
  <p>Mathematically it's just "'Duration' / '#Calls'" but after looking at some similar questions on StackOverflow, the example queries are too simple to help me relate to my one above.</p>
  
  <p>Right now, I'm not even sure that it's going to be possible to divide the time column by the number of calls.</p>
  
  <p><strong>UPDATE</strong>: I was so close in my testing but got all confused &amp; overcomplicated things.  Here's the latest SQL (thanks to @McAdam331 &amp; my buddy Jim from work): -</p>
  
  <pre><code>SELECT
      CONCAT(LEFT(u.firstname,1),LEFT(u.lastname,1)) AS Name,
      sec_to_time(SUM(
          time_to_sec(s.disconnecttimestamp) - time_to_sec(s.connecttimestamp)
      )) AS Duration,
      COUNT(*) AS '#Calls',
      sec_to_time(SUM(time_to_sec(s.disconnecttimestamp) - time_to_sec(s.connecttimestamp)) / COUNT(*)) AS Average
  FROM
      session s
      JOIN mxuser u ON
          s.ExtensionID1 = u.ExtensionId
          OR s.ExtensionID2 = u.ExtensionId
  WHERE
      s.ServiceExtension1 IS NULL
      AND s.connecttimestamp &gt;= CURRENT_DATE
      AND BINARY u.userprofilename = BINARY 'DBAM'
  GROUP BY
      u.firstname,
      u.lastname
  ORDER BY
      Average DESC;
  </code></pre>
  
  <p>Output is as follows: -</p>
  
  <pre>
  Name    Duration        #Calls  Average
  DS      00:14:25        4       00:03:36
  MG      00:17:23        11      00:01:34
  TS      00:33:38        22      00:01:31
  EW      01:04:31        43      00:01:30
  AS      00:49:23        33      00:01:29
  TH      00:43:57        35      00:01:15
  SH      00:13:51        12      00:01:09
  </pre>