BEGIN; BEGIN select c_count, count(*) as custdist from ( select c_custkey, count(o_orderkey) from customer left outer join orders on c_custkey = o_custkey and o_comment not like '%unusual%packages%' group by c_custkey ) as c_orders (c_custkey, c_count) group by c_count order by custdist desc, c_count desc; c_count | custdist ---------+---------- 0 | 500021 10 | 65993 9 | 65159 11 | 62261 8 | 58193 12 | 55850 13 | 49780 19 | 46801 7 | 46590 18 | 46147 14 | 45378 20 | 45287 17 | 45001 15 | 43925 16 | 43595 21 | 42172 22 | 38347 6 | 32722 23 | 32495 24 | 26973 25 | 21170 5 | 19598 26 | 15997 27 | 11750 4 | 9962 28 | 8157 29 | 5657 3 | 3971 30 | 3769 31 | 2417 32 | 1510 2 | 1182 33 | 845 34 | 501 35 | 288 1 | 232 36 | 129 37 | 83 38 | 45 39 | 22 40 | 15 42 | 3 41 | 3 45 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT