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 | 66179 9 | 65167 11 | 62019 8 | 58656 12 | 55964 13 | 49828 19 | 46637 7 | 46365 18 | 46363 20 | 45267 14 | 45155 17 | 44939 16 | 43965 15 | 43935 21 | 42102 22 | 38219 6 | 32974 23 | 32538 24 | 26706 25 | 21003 5 | 19714 26 | 15960 27 | 11688 4 | 9887 28 | 8223 29 | 5638 3 | 4045 30 | 3696 31 | 2291 32 | 1505 2 | 1193 33 | 864 34 | 493 35 | 298 1 | 227 36 | 124 37 | 63 38 | 38 39 | 23 40 | 16 42 | 5 41 | 5 45 | 2 (44 rows) COMMIT; COMMIT