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 ('13', '25', '30', '24', '29', '17', '16') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('13', '25', '30', '24', '29', '17', '16') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; cntrycode | numcust | totacctbal -----------+---------+------------- 13 | 9030 | 6.76174e+07 16 | 8983 | 6.73137e+07 17 | 9084 | 6.81695e+07 24 | 8953 | 6.71196e+07 25 | 9121 | 6.84108e+07 29 | 9216 | 6.91003e+07 30 | 9355 | 7.01789e+07 (7 rows) COMMIT; COMMIT