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 '%pending%deposits%' 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 | 66023 9 | 65317 11 | 62368 8 | 58348 12 | 55685 13 | 49846 19 | 46631 18 | 46352 7 | 46284 14 | 45332 17 | 45090 20 | 45083 16 | 43746 15 | 43693 21 | 42323 22 | 38228 6 | 32717 23 | 32656 24 | 26800 25 | 21079 5 | 19695 26 | 16164 27 | 11696 4 | 9874 28 | 8227 29 | 5752 3 | 4000 30 | 3761 31 | 2325 32 | 1496 2 | 1185 33 | 869 34 | 512 35 | 284 1 | 232 36 | 135 37 | 82 38 | 36 39 | 27 40 | 13 42 | 5 41 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT