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 '%unusual%requests%' 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 | 66223 9 | 65322 11 | 62018 8 | 58043 12 | 55984 13 | 49866 18 | 46580 19 | 46379 7 | 46342 20 | 45448 14 | 45154 17 | 44917 16 | 43986 15 | 43657 21 | 42212 22 | 37959 6 | 32837 23 | 32619 24 | 26949 25 | 21122 5 | 19748 26 | 16110 27 | 11754 4 | 9798 28 | 8297 29 | 5683 3 | 4037 30 | 3759 31 | 2394 32 | 1446 2 | 1164 33 | 890 34 | 478 35 | 276 1 | 224 36 | 142 37 | 76 38 | 36 39 | 23 40 | 14 41 | 7 42 | 5 44 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT