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 | 66067 9 | 65184 11 | 62154 8 | 58329 12 | 56159 13 | 49447 19 | 46759 7 | 46281 18 | 46238 14 | 45345 20 | 45301 17 | 45060 15 | 43910 16 | 43766 21 | 42267 22 | 38045 6 | 32778 23 | 32523 24 | 26900 25 | 21243 5 | 19737 26 | 15945 27 | 11834 4 | 9848 28 | 8198 29 | 5687 3 | 4013 30 | 3719 31 | 2434 32 | 1471 2 | 1164 33 | 865 34 | 494 35 | 298 1 | 226 36 | 120 37 | 76 38 | 44 39 | 23 40 | 17 42 | 4 44 | 2 41 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT