BEGIN; BEGIN select cntrycode, count(*) as numcust, sum(c_acctbal) as totacctbal from ( select substr(c_phone, 1, 2) as cntrycode, c_acctbal from customer where substr(c_phone, 1, 2) in ('27', '14', '30', '24', '33', '26', '21') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('27', '14', '30', '24', '33', '26', '21') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; cntrycode | numcust | totacctbal -----------+---------+------------- 14 | 9015 | 6.78114e+07 21 | 9088 | 6.82847e+07 24 | 8940 | 6.70546e+07 26 | 9021 | 6.77449e+07 27 | 9017 | 6.7656e+07 30 | 9344 | 7.0124e+07 33 | 9183 | 6.89001e+07 (7 rows) COMMIT; COMMIT