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 | 66055 9 | 65336 11 | 62322 8 | 58334 12 | 55642 13 | 49867 19 | 46583 18 | 46427 7 | 46272 14 | 45374 20 | 45106 17 | 44999 16 | 43736 15 | 43701 21 | 42352 22 | 38150 6 | 32749 23 | 32735 24 | 26721 25 | 21201 5 | 19652 26 | 16123 27 | 11702 4 | 9924 28 | 8181 29 | 5761 3 | 3992 30 | 3745 31 | 2349 32 | 1513 2 | 1179 33 | 856 34 | 515 35 | 286 1 | 235 36 | 132 37 | 81 38 | 40 39 | 24 40 | 14 42 | 5 41 | 4 43 | 2 45 | 1 44 | 1 (46 rows) COMMIT; COMMIT