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 | 66301 9 | 65042 11 | 62106 8 | 58454 12 | 55837 13 | 49900 19 | 46683 18 | 46303 7 | 46262 20 | 45400 14 | 45204 17 | 45082 16 | 43765 15 | 43669 21 | 42237 22 | 37972 6 | 32696 23 | 32678 24 | 26849 25 | 21304 5 | 19689 26 | 16032 27 | 11726 4 | 9895 28 | 8220 29 | 5623 3 | 4001 30 | 3850 31 | 2325 32 | 1522 2 | 1180 33 | 853 34 | 516 35 | 286 1 | 228 36 | 131 37 | 73 38 | 38 39 | 27 40 | 12 42 | 5 41 | 5 45 | 1 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT