From 5d3547923e422f9946b6159945180a7b349008c2 Mon Sep 17 00:00:00 2001 From: Erin Moore Date: Wed, 19 Jul 2023 13:24:56 -0400 Subject: [PATCH] A much shorter query! Co-authored-by: Matt Shanley --- apps/alert_processor/lib/model/query.ex | 30 ++++++++----------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/apps/alert_processor/lib/model/query.ex b/apps/alert_processor/lib/model/query.ex index 583cf9c4a..ae3f72047 100644 --- a/apps/alert_processor/lib/model/query.ex +++ b/apps/alert_processor/lib/model/query.ex @@ -250,27 +250,15 @@ defmodule AlertProcessor.Model.Query do %__MODULE__{ label: "Count of Active Users By Number of Active Trips", query: """ - SELECT integers.* - FROM generate_series(1, ( - SELECT COUNT(ttr.id) as trip_count from trips ttr - group by ttr.user_id - ORDER BY trip_count DESC - LIMIT 1 - )) i - CROSS JOIN LATERAL ( - SELECT i AS active_trips, COUNT(x.*) AS active_users FROM - ( - SELECT u.id FROM users u - JOIN trips tr ON tr.user_id = u.id - WHERE tr.id = ANY( - SELECT DISTINCT ss.trip_id FROM subscriptions ss - WHERE ss.paused = false - ) - GROUP BY u.id - HAVING COUNT(tr.id) = i - )x - HAVING COUNT(x) > 0 - ) integers; + select trip_count, count(user_id) as users + from ( + select t.user_id as user_id, count(distinct t.id) as trip_count + from trips t + join subscriptions s + on s.trip_id = t.id and s.paused = false + group by t.user_id + ) as user_trip_counts + group by trip_count; """ } ]