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 '%special%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 | 500018 10 | 66199 9 | 65103 11 | 62124 8 | 58279 12 | 55895 13 | 49663 18 | 46491 19 | 46357 7 | 46334 20 | 45459 14 | 45242 17 | 44979 15 | 43953 16 | 43882 21 | 42218 22 | 38115 6 | 32925 23 | 32485 24 | 26960 25 | 21131 5 | 19675 26 | 16010 27 | 11740 4 | 9809 28 | 8369 29 | 5657 3 | 4014 30 | 3740 31 | 2343 32 | 1502 2 | 1145 33 | 830 34 | 524 35 | 293 1 | 239 36 | 131 37 | 78 38 | 34 39 | 27 40 | 13 41 | 7 42 | 5 44 | 2 43 | 1 (45 rows) COMMIT; COMMIT