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 | 66097 9 | 65170 11 | 62084 8 | 58337 12 | 56147 13 | 49559 19 | 46820 7 | 46289 18 | 46257 14 | 45283 20 | 45269 17 | 45006 15 | 43977 16 | 43710 21 | 42261 22 | 38035 6 | 32762 23 | 32546 24 | 26865 25 | 21251 5 | 19719 26 | 15966 27 | 11832 4 | 9874 28 | 8168 29 | 5693 3 | 4014 30 | 3752 31 | 2406 32 | 1493 2 | 1168 33 | 862 34 | 487 35 | 304 1 | 226 36 | 121 37 | 73 38 | 47 39 | 22 40 | 17 42 | 4 45 | 2 41 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT