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%requests%' 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 | 500018 10 | 66178 9 | 65348 11 | 62016 8 | 58087 12 | 55938 13 | 49896 18 | 46589 19 | 46334 7 | 46312 20 | 45491 14 | 45165 17 | 44852 16 | 44070 15 | 43619 21 | 42298 22 | 37899 6 | 32859 23 | 32631 24 | 26952 25 | 21079 5 | 19728 26 | 16129 27 | 11788 4 | 9822 28 | 8250 29 | 5694 3 | 4026 30 | 3727 31 | 2410 32 | 1462 2 | 1158 33 | 892 34 | 479 35 | 276 1 | 226 36 | 137 37 | 74 38 | 39 39 | 21 40 | 15 41 | 7 42 | 5 44 | 3 43 | 1 (45 rows) COMMIT; COMMIT