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 '%express%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 | 500018 10 | 65970 9 | 65272 11 | 62343 8 | 58227 12 | 55976 13 | 49731 19 | 46676 7 | 46279 18 | 46146 20 | 45408 14 | 45249 17 | 45041 15 | 43780 16 | 43763 21 | 42535 22 | 37854 6 | 32843 23 | 32633 24 | 26811 25 | 21165 5 | 19687 26 | 16097 27 | 11744 4 | 9820 28 | 8202 29 | 5727 3 | 4022 30 | 3804 31 | 2347 32 | 1492 2 | 1163 33 | 870 34 | 498 35 | 274 1 | 227 36 | 143 37 | 73 38 | 35 39 | 25 40 | 16 41 | 7 43 | 3 45 | 2 44 | 1 42 | 1 (46 rows) COMMIT; COMMIT