QUERY PLAN
Aggregate (cost=720.14..720.15 rows=1 width=32)
-> GroupAggregate (cost=718.79..719.58 rows=45 width=36)
Group Key: sub.id2
-> Sort (cost=718.79..718.90 rows=45 width=36)
Sort Key: sub.id2
-> Subquery Scan on sub (cost=716.99..717.56 rows=45 width=36)
-> Sort (cost=716.99..717.11 rows=45 width=603)
Sort Key: (CASE WHEN (t0_1.id IS NOT NULL) THEN t0_1.remind_date ELSE sc.signed_at END) DESC
-> Nested Loop (cost=668.07..715.76 rows=45 width=603)
-> 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=668.07..713.54 rows=45 width=52)
Hash Cond: (t0.id = sc.id)
-> HashAggregate (cost=149.84..171.27 rows=1715 width=36)
Group Key: t0.id
-> Hash Right Join (cost=89.76..139.68 rows=2032 width=17)
Hash Cond: (t1.contract_id = t0.id)
-> Seq Scan on tbl_sales_contract_invoices t1 (cost=0.00..44.52 rows=2052 width=10)
-> Hash (cost=68.32..68.32 rows=1715 width=11)
-> Seq Scan on tbl_sales_contracts t0 (cost=0.00..68.32 rows=1715 width=11)
Filter: need_analysis
-> Hash (cost=517.68..517.68 rows=45 width=20)
-> Hash Right Join (cost=502.55..517.68 rows=45 width=20)
Hash Cond: (t0_1.contract_id = sc.id)
Filter: (((t0_1.id IS NOT NULL) AND (t0_1.paid_amount <> '0'::numeric)) OR ((t0_1.id IS NULL) AND (sc.erp_settle_amount > '0'::numeric)))
-> HashAggregate (cost=328.56..334.82 rows=626 width=67)
Group Key: t0_1.id
-> Hash Join (cost=292.33..327.00 rows=626 width=18)
Hash Cond: (t0_1.contract_id = t1_1.id)
-> Seq Scan on tbl_sales_contract_payment_collection_remind_dates t0_1 (cost=0.00..23.93 rows=1193 width=18)
-> Hash (cost=280.97..280.97 rows=909 width=4)
-> Hash Join (cost=208.21..280.97 rows=909 width=4)
Hash Cond: (t1_1.from_project = p.id)
-> Seq Scan on tbl_sales_contracts t1_1 (cost=0.00..68.32 rows=1686 width=8)
Filter: (need_analysis AND (from_project IS NOT NULL))
-> Hash (cost=186.78..186.78 rows=1715 width=4)
-> Seq Scan on tbl_projects p (cost=0.00..186.78 rows=1715 width=4)
Filter: (project_status = 3)
-> Hash (cost=173.42..173.42 rows=46 width=18)
-> Hash Join (cost=100.57..173.42 rows=46 width=18)
Hash Cond: (sc.client_id = c.id)
-> Seq Scan on tbl_sales_contracts sc (cost=0.00..68.32 rows=1720 width=22)
Filter: build_by_project
-> Hash (cost=99.91..99.91 rows=53 width=8)
-> Bitmap Heap Scan on tbl_clients c (cost=4.82..99.91 rows=53 width=8)
Recheck Cond: (sales_rep = 1001)
-> Bitmap Index Scan on tbl_clients_sales_rep_idx (cost=0.00..4.80 rows=70 width=0)
Index Cond: (sales_rep = 1001)