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%packages%' 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 | 500020 10 | 66002 9 | 65236 11 | 62198 8 | 58197 12 | 56134 13 | 49600 19 | 46632 18 | 46472 7 | 46343 20 | 45406 14 | 45158 17 | 44889 15 | 44019 16 | 43796 21 | 42104 22 | 38068 6 | 32781 23 | 32517 24 | 26988 25 | 21161 5 | 19763 26 | 15988 27 | 11806 4 | 9832 28 | 8213 29 | 5719 3 | 4025 30 | 3686 31 | 2433 32 | 1501 2 | 1159 33 | 839 34 | 497 35 | 294 1 | 226 36 | 133 37 | 72 38 | 41 39 | 24 40 | 16 41 | 5 42 | 3 45 | 2 44 | 1 43 | 1 (46 rows) COMMIT; COMMIT