QUERY PLAN
Aggregate (cost=783.00..783.01 rows=1 width=32)
-> Group (cost=782.82..782.89 rows=9 width=42)
Group Key: sc.id2, tbl_sales_contracts.erp_settle_amount
-> Sort (cost=782.82..782.84 rows=9 width=10)
Sort Key: sc.id2, tbl_sales_contracts.erp_settle_amount
-> Hash Right Join (cost=741.62..782.68 rows=9 width=10)
Hash Cond: (tbl_sales_contracts.id = sc.id2)
-> HashAggregate (cost=122.56..139.81 rows=1725 width=10)
Group Key: tbl_sales_contracts.id
-> Seq Scan on tbl_sales_contracts (cost=0.00..118.25 rows=1725 width=10)
-> Hash (cost=619.04..619.04 rows=1 width=4)
-> Subquery Scan on sc (cost=619.03..619.04 rows=1 width=4)
-> Sort (cost=619.03..619.03 rows=1 width=571)
Sort Key: (CASE WHEN (t0.id IS NOT NULL) THEN t0.remind_date ELSE sc_1.signed_at END) DESC
-> Nested Loop (cost=478.60..619.02 rows=1 width=571)
-> Nested Loop Left Join (cost=478.60..617.24 rows=1 width=20)
Join Filter: (t0.contract_id = sc_1.id)
-> Hash Join (cost=99.40..217.69 rows=1 width=12)
Hash Cond: (sc_1.client_id = c.id)
-> Seq Scan on tbl_sales_contracts sc_1 (cost=0.00..118.25 rows=17 width=16)
Filter: (build_by_project AND (NOT need_analysis))
-> Hash (cost=98.78..98.78 rows=50 width=8)
-> Bitmap Heap Scan on tbl_clients c (cost=4.79..98.78 rows=50 width=8)
Recheck Cond: (sales_rep = 1001)
-> Bitmap Index Scan on tbl_clients_sales_rep_idx (cost=0.00..4.78 rows=67 width=0)
Index Cond: (sales_rep = 1001)
-> HashAggregate (cost=379.20..385.46 rows=626 width=93)
Group Key: t0.id
-> Hash Join (cost=180.87..377.64 rows=626 width=12)
Hash Cond: (p.id = t1.from_project)
-> Seq Scan on tbl_projects p (cost=0.00..184.28 rows=1691 width=4)
Filter: (project_status = 3)
-> Hash (cost=166.34..166.34 rows=1163 width=16)
-> Hash Join (cost=139.24..166.34 rows=1163 width=16)
Hash Cond: (t0.contract_id = t1.id)
-> Seq Scan on tbl_sales_contract_payment_collection_remind_dates t0 (cost=0.00..23.95 rows=1195 width=12)
-> Hash (cost=118.25..118.25 rows=1679 width=8)
-> Seq Scan on tbl_sales_contracts t1 (cost=0.00..118.25 rows=1679 width=8)
Filter: (need_analysis AND (from_project IS NOT NULL))
-> 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))