QUERY PLAN
Aggregate (cost=107.17..107.18 rows=1 width=32)
-> GroupAggregate (cost=106.86..107.04 rows=10 width=36)
Group Key: sub.id2
-> Sort (cost=106.86..106.89 rows=10 width=36)
Sort Key: sub.id2
-> Subquery Scan on sub (cost=106.57..106.70 rows=10 width=36)
-> Sort (cost=106.57..106.60 rows=10 width=571)
Sort Key: (CASE WHEN (scpcrds.id IS NOT NULL) THEN scpcrds.remind_date ELSE sc.signed_at END) DESC
-> Nested Loop Left Join (cost=76.47..106.41 rows=10 width=571)
-> Nested Loop Left Join (cost=76.32..88.35 rows=1 width=52)
Join Filter: (t0_1.id = sc.id)
-> Hash Left Join (cost=51.99..62.81 rows=1 width=20)
Hash Cond: (sc.id = scpcrds.contract_id)
Filter: (((scpcrds.id IS NOT NULL) AND (scpcrds.paid_amount <> '0'::numeric)) OR ((scpcrds.id IS NULL) AND (sc.erp_settle_amount > '0'::numeric)))
-> Hash Left Join (cost=10.45..21.24 rows=2 width=44)
Hash Cond: (sc.client_id = c.id)
Filter: ((c.sales_rep = 5493) OR (c.sales_rep IS NULL))
-> Seq Scan on tbl_sales_contracts sc (cost=0.00..10.70 rows=35 width=48)
Filter: build_by_project
-> 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)
-> Hash (cost=41.50..41.50 rows=3 width=44)
-> Subquery Scan on scpcrds (cost=41.46..41.50 rows=3 width=44)
-> 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)
-> HashAggregate (cost=24.32..24.76 rows=35 width=36)
Group Key: t0_1.id
-> Hash Right Join (cost=11.14..23.80 rows=105 width=69)
Hash Cond: (t1_1.contract_id = t0_1.id)
-> Seq Scan on tbl_sales_contract_invoices t1_1 (cost=0.00..12.10 rows=210 width=36)
-> Hash (cost=10.70..10.70 rows=35 width=37)
-> Seq Scan on tbl_sales_contracts t0_1 (cost=0.00..10.70 rows=35 width=37)
Filter: need_analysis
-> 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)