QUERY PLAN
Aggregate (cost=359.81..359.82 rows=1 width=32)
-> Hash Left Join (cost=282.16..359.65 rows=32 width=42)
Hash Cond: (t.id = sub.contract_id)
Filter: (CASE WHEN (cancel.sales_contract_id IS NULL) THEN t.amount ELSE '0'::numeric END >= COALESCE(sub.amount, '0'::numeric))
-> Hash Left Join (cost=68.08..145.31 rows=97 width=14)
Hash Cond: (t.id = cancel.sales_contract_id)
-> Seq Scan on tbl_sales_contracts t (cost=0.00..76.98 rows=97 width=10)
Filter: (build_by_project AND (id IS NOT NULL) AND (created_at >= '2025-08-08 14:34:58+08'::timestamp with time zone) AND (created_at <= '2025-12-31 23:59:59+08'::timestamp with time zone))
-> Hash (cost=68.07..68.07 rows=1 width=4)
-> Subquery Scan on cancel (cost=68.04..68.07 rows=1 width=4)
-> GroupAggregate (cost=68.04..68.06 rows=1 width=12)
Group Key: t_1.sales_contract_id
-> Sort (cost=68.04..68.05 rows=1 width=4)
Sort Key: t_1.sales_contract_id
-> Seq Scan on tbl_erp_sales_orders t_1 (cost=0.00..68.03 rows=1 width=4)
Filter: ((cancel_at >= '2025-08-08 14:34:58+08'::timestamp with time zone) AND (cancel_at <= '2025-12-31 23:59:59+08'::timestamp with time zone) AND (status = 8))
-> Hash (cost=212.36..212.36 rows=138 width=36)
-> Subquery Scan on sub (cost=209.25..212.36 rows=138 width=36)
-> HashAggregate (cost=209.25..210.98 rows=138 width=36)
Group Key: "*SELECT* 1".contract_id
-> Append (cost=70.66..208.56 rows=138 width=10)
-> Subquery Scan on "*SELECT* 1" (cost=70.66..113.65 rows=136 width=10)
-> Hash Join (cost=70.66..112.29 rows=136 width=106)
Hash Cond: (r.erp_collect_ticket_id = t_2.id)
-> Seq Scan on tbl_erp_collect_ticket_settles r (cost=0.00..35.94 rows=2160 width=14)
Filter: (sales_contract_id IS NOT NULL)
-> Hash (cost=68.94..68.94 rows=138 width=4)
-> Seq Scan on tbl_erp_collect_tickets t_2 (cost=0.00..68.94 rows=138 width=4)
Filter: ((bank_settle_at <= '2025-12-31 23:59:59+08'::timestamp with time zone) AND (status = 2))
-> Subquery Scan on "*SELECT* 2" (cost=0.29..9.36 rows=1 width=9)
-> Nested Loop (cost=0.29..9.35 rows=1 width=105)
-> Seq Scan on tbl_erp_cash_cost_ticket_sales_contract_settles r_1 (cost=0.00..1.02 rows=1 width=13)
Filter: (sales_contract_id IS NOT NULL)
-> Index Scan using tbl_erp_cash_cost_tickets_pkey on tbl_erp_cash_cost_tickets t_3 (cost=0.29..8.31 rows=1 width=4)
Index Cond: (id = r_1.erp_cash_cost_ticket_id)
Filter: (is_payment_settle AND (bank_settle_at <= '2025-12-31 23:59:59+08'::timestamp with time zone) AND (status = 2))
-> Subquery Scan on "*SELECT* 3" (cost=0.28..85.56 rows=1 width=36)
-> Nested Loop (cost=0.28..85.55 rows=1 width=132)
-> Seq Scan on tbl_erp_payment_ticket_settles r_2 (cost=0.00..39.65 rows=6 width=14)
Filter: (sales_contract_id IS NOT NULL)
-> Index Scan using tbl_erp_payment_tickets_pkey on tbl_erp_payment_tickets t_4 (cost=0.28..7.64 rows=1 width=4)
Index Cond: (id = r_2.erp_payment_ticket_id)
Filter: (is_payment_settle AND (bank_settle_at <= '2025-12-31 23:59:59+08'::timestamp with time zone) AND (status = 2))