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%accounts%' 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 | 500016 10 | 66305 9 | 65032 11 | 62174 8 | 58402 12 | 55775 13 | 49841 19 | 46683 18 | 46321 7 | 46304 20 | 45316 14 | 45281 17 | 45088 16 | 43776 15 | 43654 21 | 42306 22 | 37957 6 | 32728 23 | 32669 24 | 26907 25 | 21243 5 | 19707 26 | 16039 27 | 11758 4 | 9856 28 | 8205 29 | 5633 3 | 3997 30 | 3798 31 | 2369 32 | 1508 2 | 1175 33 | 871 34 | 496 35 | 288 1 | 227 36 | 131 37 | 76 38 | 35 39 | 28 40 | 12 42 | 6 41 | 5 45 | 1 44 | 1 (45 rows) COMMIT; COMMIT