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 | 65444 11 | 62182 8 | 58329 12 | 56006 13 | 49713 19 | 46571 18 | 46467 7 | 46415 20 | 45284 14 | 45270 17 | 45263 15 | 43810 16 | 43715 21 | 42168 22 | 37992 6 | 32933 23 | 32628 24 | 26708 25 | 20876 5 | 19873 26 | 16101 27 | 11571 4 | 9852 28 | 8255 29 | 5640 3 | 4036 30 | 3689 31 | 2343 32 | 1506 2 | 1178 33 | 824 34 | 497 35 | 292 1 | 232 36 | 130 37 | 73 38 | 36 39 | 27 40 | 14 42 | 5 41 | 5 45 | 1 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT