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 | 66209 9 | 65166 11 | 62279 8 | 58396 12 | 55514 13 | 49979 19 | 46683 18 | 46364 7 | 46254 14 | 45431 20 | 45202 17 | 44914 16 | 43815 15 | 43609 21 | 42358 22 | 38127 6 | 32799 23 | 32494 24 | 26829 25 | 21332 5 | 19585 26 | 16055 27 | 11774 4 | 9927 28 | 8251 29 | 5677 3 | 3976 30 | 3737 31 | 2334 32 | 1503 2 | 1195 33 | 861 34 | 508 35 | 310 1 | 234 36 | 132 37 | 73 38 | 48 39 | 18 40 | 11 42 | 5 41 | 5 45 | 2 43 | 2 44 | 1 (46 rows) COMMIT; COMMIT