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 | 66123 9 | 65287 11 | 62154 8 | 58394 12 | 56093 13 | 49448 19 | 46730 7 | 46446 18 | 46359 14 | 45318 20 | 45263 17 | 45083 15 | 44035 16 | 43803 21 | 42246 22 | 37977 6 | 32898 23 | 32394 24 | 26822 25 | 21086 5 | 19843 26 | 15871 27 | 11726 4 | 9903 28 | 8148 29 | 5618 3 | 4038 30 | 3689 31 | 2414 32 | 1465 2 | 1174 33 | 833 34 | 488 35 | 297 1 | 228 36 | 119 37 | 74 38 | 43 39 | 22 40 | 17 42 | 4 44 | 2 41 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT