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%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 | 500021 10 | 66050 9 | 65190 11 | 62098 8 | 58371 12 | 55968 13 | 49875 19 | 46822 18 | 46416 7 | 46344 14 | 45390 20 | 45129 17 | 44783 15 | 43701 16 | 43641 21 | 42516 22 | 37991 6 | 32812 23 | 32579 24 | 26940 25 | 21067 5 | 19608 26 | 16132 27 | 11710 4 | 9850 28 | 8305 29 | 5687 3 | 4030 30 | 3765 31 | 2348 32 | 1508 2 | 1180 33 | 859 34 | 508 35 | 295 1 | 215 36 | 134 37 | 67 38 | 42 39 | 27 40 | 12 41 | 6 42 | 4 44 | 2 45 | 1 43 | 1 (46 rows) COMMIT; COMMIT