Search code examples
sqlitereportspiceworks

Add average time to last row of query using sqlite


I have the following report that runs on a Spiceworks server weekly for our IS and IT departments to use as a metric for how long it takes us to assign helpdesk tickets. It selects the following:

  • ticket ID
  • ticket create date
  • calculates the time it took to assign (assigned time - create time)
  • who the ticket is assigned to
  • who assigned the ticket

The where clause finds the comment with the "Assigned to" information and only grabs tickets from the past 7 days that were assigned to the users in the IT department.

I'm trying to add a final row to this query that will average the time it took for the department to assign a ticket. I read about the rollup() function, but it's not a recognized Sqlite method.

Any tips or suggestions would be great! Thanks!

--Based on report by Ben Brookshire, Spiceworks Inc.
SELECT t.id as ID,
   t.created_at as TicketCreated,

  --CASE WHEN x=w1 THEN r1 WHEN x=w2 THEN r2 ELSE r3 END
  CASE
  WHEN (((strftime('%s',c.created_at) - strftime('%s',t.created_at))/60) < 1) THEN   (strftime('%s',c.created_at) - strftime('%s',t.created_at)) || " seconds"
  WHEN (((strftime('%s',c.created_at) - strftime('%s',t.created_at))/3600) < 1) THEN round((strftime('%s',c.created_at) - strftime('%s',t.created_at))/60,3) || " minutes"
  WHEN (((strftime('%s',c.created_at) - strftime('%s',t.created_at))/3600) > 1) THEN round((strftime('%s',c.created_at) - strftime('%s',t.created_at))/3600.0,3) || " hours"
  WHEN (((strftime('%s',c.created_at) - strftime('%s',t.created_at))/3600) > 24) THEN round((strftime('%s',c.created_at) - strftime('%s',t.created_at))/86400.0,3) || " days"
 ELSE "error"
 --round((strftime('%s',c.created_at) - strftime('%s',t.created_at))/3600.0,3) as "Time to Assign (hours)",
 END as "Time to Assign",
 u.email as AssignedTo,
 u2.email as AssignedBy

FROM tickets t

  LEFT JOIN comments c ON c.ticket_id = t.id
  LEFT JOIN users u ON u.id = t.assigned_to
  LEFT JOIN users u2 ON u2.id = c.created_by

WHERE c.body LIKE "%Assigned to%"
  AND c.created_at BETWEEN date('now', '-6 days') AND date('now')
  AND (u.email = "[email protected]" OR u.email = "[email protected]")
ORDER BY t.id;​

Solution

  • Compute the average with a separate query, and add that record using a compound query:

    SELECT t.id, ...
    FROM ...
    WHERE ...
    UNION ALL
    SELECT 999999999, NULL,
           AVG(strftime('%s', c.created_at) - strftime('%s', t.created_at)),
           NULL, NULL
    FROM ...
    WHERE ...
    ORDER BY 1