I would like to find out the average time that a client waits on a response from a project manager in a chat conversation.
I need to make sure it only calculates the waiting time for the last client message in a row. E.g. the client writes five messages in a row and then the account manager answers two hours later, then we should ignore the first four messages from the client.
I am also only interested in project conversations, so I need to ignore task conversations.
We are using PostgreSQL 14.7.
The tables looks like this (simplified):
users
id | role |
---|---|
153 | account_manager |
157 | client |
role is either client or account_manager
conversations
id | object_type |
---|---|
12 | project |
13 | task |
object_type is either project or task
messages
id | user_id | conversation_id | created_at |
---|---|---|---|
1133 | 157 | 12 | 2023-04-19 13:05:48 |
1157 | 157 | 12 | 2023-04-19 13:06:00 |
1163 | 157 | 12 | 2023-04-19 13:15:00 |
1178 | 153 | 12 | 2023-04-19 14:15:00 |
1209 | 157 | 12 | 2023-04-20 10:23:00 |
1327 | 153 | 12 | 2023-04-20 14:23:00 |
In the example above the average time would be (1+4)/2= 2,5 hours
I would also like to know how that number changes over time, so I would need it grouped per month.
Thanks a lot for any help on this!
I have tried various approaches without success.
2
Answers
Take rows where with role account_amanger and previous role client, use lag(). Then count average:
dbfiddle demo
Here is the test data :
And now the query :