Created
January 22, 2015 07:10
-
-
Save mberman84/08cce1b0979b0d817e4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def calculate_response_time_per_message | |
| Message.connection.execute(" | |
| SELECT q3.id, q3.customer_id, DATE(q3.created_at AT TIME ZONE '-08:00') AS date, EXTRACT(EPOCH FROM q3.created_at) AS created_at, EXTRACT(EPOCH FROM q3.response_time) AS response_time FROM | |
| (SELECT q2.*, | |
| CASE WHEN direction = 'received' THEN LEAD(created_at) OVER (PARTITION BY customer_id ORDER BY created_at) - created_at | |
| ELSE NULL | |
| END AS response_time FROM | |
| (SELECT q1.id, q1.customer_id, q1.created_at, q1.direction FROM | |
| (SELECT m.id, m.customer_id, m.created_at, m.direction, LAG(direction) OVER (PARTITION BY customer_id ORDER BY created_at) AS prev_direction FROM messages m | |
| WHERE company_id = 2 AND via_api = false AND mass_message_id IS NULL) AS q1 | |
| WHERE (q1.direction = 'received' AND q1.prev_direction IS DISTINCT FROM 'received') OR (q1.direction = 'sent' AND q1.prev_direction = 'received')) AS q2 | |
| ) AS q3 | |
| WHERE q3.direction = 'received' AND q3.response_time IS NOT NULL ORDER BY created_at DESC | |
| ") | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment