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 | 66081 9 | 65379 11 | 62213 8 | 58279 12 | 56010 13 | 49742 19 | 46715 18 | 46522 7 | 46411 20 | 45269 17 | 45222 14 | 45198 15 | 43935 16 | 43564 21 | 42034 22 | 38026 6 | 32986 23 | 32570 24 | 26810 25 | 20820 5 | 19878 26 | 16122 27 | 11590 4 | 9818 28 | 8239 29 | 5640 3 | 4050 30 | 3715 31 | 2330 32 | 1487 2 | 1179 33 | 825 34 | 495 35 | 302 1 | 233 36 | 123 37 | 76 38 | 37 39 | 24 40 | 17 42 | 5 41 | 5 45 | 2 43 | 1 (45 rows) COMMIT; COMMIT