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 | 66050 9 | 65306 11 | 62316 8 | 58312 12 | 55668 13 | 49927 19 | 46683 18 | 46409 7 | 46358 14 | 45364 20 | 45108 17 | 44997 16 | 43708 15 | 43663 21 | 42243 22 | 38154 23 | 32782 6 | 32752 24 | 26730 25 | 21243 5 | 19597 26 | 16096 27 | 11645 4 | 9918 28 | 8201 29 | 5742 3 | 3993 30 | 3747 31 | 2375 32 | 1516 2 | 1182 33 | 851 34 | 517 35 | 276 1 | 237 36 | 144 37 | 79 38 | 38 39 | 26 40 | 13 42 | 5 41 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT