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 | 66078 9 | 65278 11 | 62316 8 | 58295 12 | 55615 13 | 50040 19 | 46628 7 | 46420 18 | 46330 14 | 45191 20 | 45176 17 | 45011 15 | 43786 16 | 43690 21 | 42287 22 | 38182 23 | 32809 6 | 32735 24 | 26702 25 | 21277 5 | 19583 26 | 16064 27 | 11582 4 | 9933 28 | 8240 29 | 5741 3 | 3987 30 | 3742 31 | 2357 32 | 1532 2 | 1180 33 | 854 34 | 511 35 | 280 1 | 234 36 | 146 37 | 78 38 | 40 39 | 24 40 | 12 42 | 5 41 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT