QUERY PLAN
Aggregate (cost=94.23..94.24 rows=1 width=32)
-> Group (cost=94.03..94.10 rows=10 width=68)
Group Key: sc.id2, tbl_sales_contracts.erp_settle_amount
-> Sort (cost=94.03..94.05 rows=10 width=36)
Sort Key: sc.id2, tbl_sales_contracts.erp_settle_amount
-> Hash Right Join (cost=92.10..93.86 rows=10 width=36)
Hash Cond: (tbl_sales_contracts.id = sc.id2)
-> HashAggregate (cost=10.88..11.57 rows=70 width=36)
Group Key: tbl_sales_contracts.id
-> Seq Scan on tbl_sales_contracts (cost=0.00..10.70 rows=70 width=36)
-> Hash (cost=81.10..81.10 rows=10 width=4)
-> Subquery Scan on sc (cost=80.97..81.10 rows=10 width=4)
-> Sort (cost=80.97..81.00 rows=10 width=571)
Sort Key: (CASE WHEN (t0.id IS NOT NULL) THEN t0.remind_date ELSE sc_1.signed_at END) DESC
-> Nested Loop Left Join (cost=52.06..80.81 rows=10 width=571)
-> Nested Loop Left Join (cost=51.91..62.75 rows=1 width=20)
Join Filter: (t0.contract_id = sc_1.id)
Filter: (((t0.id IS NOT NULL) AND (t0.paid_amount <> '0'::numeric)) OR ((t0.id IS NULL) AND (sc_1.erp_settle_amount > '0'::numeric)))
-> Hash Left Join (cost=10.45..21.20 rows=1 width=44)
Hash Cond: (sc_1.client_id = c.id)
Filter: ((c.sales_rep = 5493) OR (c.sales_rep IS NULL))
-> Seq Scan on tbl_sales_contracts sc_1 (cost=0.00..10.70 rows=18 width=48)
Filter: (build_by_project AND (NOT need_analysis))
-> Hash (cost=10.20..10.20 rows=20 width=8)
-> Seq Scan on tbl_clients c (cost=0.00..10.20 rows=20 width=8)
-> Group (cost=41.46..41.47 rows=3 width=93)
Group Key: t0.id
-> Sort (cost=41.46..41.47 rows=3 width=44)
Sort Key: t0.id
-> Hash Join (cost=22.19..41.43 rows=3 width=44)
Hash Cond: (t0.contract_id = t1.id)
-> Seq Scan on tbl_sales_contract_payment_collection_remind_dates t0 (cost=0.00..16.70 rows=670 width=44)
-> Hash (cost=22.18..22.18 rows=1 width=4)
-> Hash Join (cost=11.39..22.18 rows=1 width=4)
Hash Cond: (t1.from_project = p.id)
-> Seq Scan on tbl_sales_contracts t1 (cost=0.00..10.70 rows=35 width=8)
Filter: (need_analysis AND (from_project IS NOT NULL))
-> Hash (cost=11.38..11.38 rows=1 width=4)
-> Seq Scan on tbl_projects p (cost=0.00..11.38 rows=1 width=4)
Filter: (project_status = 3)
-> Index Only Scan using tbl_sales_group_relationships_pkey on tbl_sales_group_relationships sgr (cost=0.15..17.95 rows=10 width=4)
Index Cond: (sales_id = c.sales_rep)