QUERY PLAN
Aggregate (cost=471.53..471.54 rows=1 width=8)
-> Sort (cost=470.66..470.80 rows=58 width=1525)
Sort Key: (CASE WHEN ((sum(CASE WHEN (p.project_status = 3) THEN p.budget ELSE '0'::numeric END)) IS NULL) THEN '0'::numeric ELSE (sum(CASE WHEN (p.project_status = 3) THEN p.budget ELSE '0'::numeric END)) END) DESC, c.created_at DESC
-> Nested Loop (cost=411.09..468.96 rows=58 width=1525)
-> Seq Scan on tbl_sales_group_relationships sgr (cost=0.00..1.77 rows=1 width=4)
Filter: ((sales_id = 1001) AND (group_id = 1))
-> Hash Right Join (cost=411.09..466.61 rows=58 width=44)
Hash Cond: ((csrr.sales_rep = c.sales_rep) AND (csrr.client_id = c.id))
-> Hash Join (cost=75.90..131.09 rows=44 width=8)
Hash Cond: (csrr.id = "ANY_subquery".max)
-> Seq Scan on tbl_client_sales_rep_rels csrr (cost=0.00..54.46 rows=89 width=12)
Filter: (sales_rep = 1001)
-> Hash (cost=73.40..73.40 rows=200 width=4)
-> HashAggregate (cost=71.40..73.40 rows=200 width=4)
Group Key: "ANY_subquery".max
-> Subquery Scan on "ANY_subquery" (cost=52.50..69.30 rows=840 width=4)
-> HashAggregate (cost=52.50..60.90 rows=840 width=8)
Group Key: csrrs.client_id
-> Seq Scan on tbl_client_sales_rep_rels csrrs (cost=0.00..47.57 rows=986 width=8)
Filter: (end_at IS NULL)
-> Hash (cost=334.32..334.32 rows=58 width=48)
-> Hash Right Join (cost=312.11..334.32 rows=58 width=48)
Hash Cond: (p.client_id = c.id)
-> HashAggregate (cost=202.77..213.82 rows=884 width=296)
Group Key: p.client_id
-> Seq Scan on tbl_projects p (cost=0.00..189.50 rows=1769 width=13)
Filter: (project_status = ANY ('{1,2,3}'::integer[]))
-> Hash (cost=108.61..108.61 rows=58 width=28)
-> Bitmap Heap Scan on tbl_clients c (cost=14.46..108.61 rows=58 width=28)
Recheck Cond: (sales_rep = 1001)
Filter: (NOT deleted)
-> Bitmap Index Scan on tbl_clients_sales_rep_idx (cost=0.00..4.78 rows=67 width=0)
Index Cond: (sales_rep = 1001)