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%accounts%' 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 | 500022 10 | 66014 9 | 65269 11 | 62264 8 | 58237 12 | 55882 13 | 49789 18 | 46547 19 | 46534 7 | 46306 20 | 45347 14 | 45283 17 | 44949 16 | 43934 15 | 43581 21 | 42297 22 | 37956 6 | 32882 23 | 32636 24 | 26842 25 | 21183 5 | 19675 26 | 16088 27 | 11791 4 | 9774 28 | 8310 29 | 5643 3 | 4031 30 | 3693 31 | 2385 32 | 1486 2 | 1177 33 | 864 34 | 513 35 | 294 1 | 224 36 | 140 37 | 65 38 | 43 39 | 23 40 | 12 41 | 7 42 | 3 44 | 2 43 | 2 45 | 1 (46 rows) COMMIT; COMMIT