Reputation: 33
I have a worklog table that contains the following fields:
worklog_id,
agent_name,
ticket_number,
timestamp,
worklog_notes.
I would like to be able to count the number of worklog entries made where if the agent_name
, ticket_number
and timestamp
(date) are the same the worklog entry is only counted if the time between the two entries is greater than 1 hour.
Example: John Smith make three worklog entries on ticket 12345. The first timestamp is "10/11/2012 9:11:44 AM", the second timestamp is "10/11/2012 9:36:16 AM" and the third timestamp is "10/11/2012 11:18:20 AM". In this example I would only want to give the agent credit for two worklog entries as the first two were less than an hour apart.
I've tried getting the logic to work using a "where" sub-query, but cannot get it working. Would anyone have any example they could provide? Thanks! :)
Upvotes: 2
Views: 502
Reputation: 48121
Does this get what you want? The first entry by a given agent on a ticket should always be counted, and entries after that should only be counted if at least an hour has elapsed since the prior entry.
select agent_name, ticket_number, count(*) from (
select agent_name, ticket_number, timestamp,
lag(timestamp) over
(partition by agent_name, ticket_number order by timestamp) prev_timestamp
)
from worklog
where (prev_timestamp is null
or (timestamp - prev_timestamp) >= interval '1' hour
)
group by agent_name, ticket_number
I'm not sure this is exactly what you want -- if an agent keeps adding entries within an hour of the prior entry, none of them will be counted except the first. So someone who adds a lot of updates gets penalized.
Maybe what you really want is to count the number of distinct hours in which an update was made:
select agent_name, ticket_number, count(distinct to_char(timestamp,'DD-MON-YYYY HH24')
from worklog
group by agent_name, ticket_number
Upvotes: 1