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%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 | 500021 10 | 66156 9 | 65191 11 | 62144 8 | 58586 12 | 55807 13 | 49872 19 | 46671 7 | 46417 18 | 46336 14 | 45217 20 | 45192 17 | 44897 16 | 43978 15 | 43910 21 | 42096 22 | 38408 6 | 32944 23 | 32411 24 | 26669 25 | 21097 5 | 19706 26 | 15945 27 | 11672 4 | 9925 28 | 8224 29 | 5618 3 | 4031 30 | 3698 31 | 2291 32 | 1502 2 | 1195 33 | 872 34 | 503 35 | 284 1 | 230 36 | 127 37 | 68 38 | 38 39 | 25 40 | 13 41 | 6 42 | 5 45 | 2 (44 rows) COMMIT; COMMIT